如何在Angular项目中配置ts-transformer-minify-privates?
解决Angular中ts-transformer-minify-privates私有字段未压缩问题
你的配置无效的核心原因是:Angular构建依赖@ngtools/webpack的AngularCompilerPlugin处理TypeScript编译,而非你新增的ts-loader,所以你添加的自定义loader规则根本不会被执行,私有字段压缩逻辑没注入到Angular的编译流程中。
按以下步骤修复:
1. 清理冗余依赖
卸载不需要的ts-loader:
npm uninstall ts-loader
2. 修正custom-webpack.config.js
直接修改Angular默认的编译插件,注入自定义transformer:
const minifyPrivatesTransformer = require('ts-transformer-minify-privates').default; module.exports = (config) => { // 定位AngularCompilerPlugin实例 const angularCompilerPlugin = config.plugins.find( plugin => plugin.constructor.name === 'AngularCompilerPlugin' ); if (angularCompilerPlugin) { // 将压缩transformer注入到编译的before阶段 angularCompilerPlugin._options.transformers = { before: [minifyPrivatesTransformer] }; } return config; };
3. 完善angular.json配置
确保你的项目配置结构完整,且生产模式开启优化:
"projects": { "your-project-name": { // 替换为你的实际项目名称 "architect": { "build": { "builder": "@angular-builders/custom-webpack:browser", "options": { "customWebpackConfig": { "path": "./custom-webpack.config.js", "replaceDuplicatePlugins": true }, // 保留你原有其他配置(如outputPath、index、main等) }, "configurations": { "production": { "optimization": true, // 确保生产模式开启优化 // 其他生产环境配置 } } } } } }
4. 移除tsconfig.json中的无效配置
删掉compilerOptions下的plugins数组,Angular构建不会读取该配置来应用transformer:
// tsconfig.json "compilerOptions": { // 保留你的其他编译配置,移除plugins部分 }
5. 重新执行生产构建
运行生产环境构建命令(开发环境可能不启用完整优化):
npm run build -- --configuration production
完成以上步骤后,私有字段会在Angular编译阶段被正确压缩。
内容的提问来源于stack exchange,提问作者ar099968
相关产品推荐
相关产品推荐

