我目前在我的应用程序中使用 Angular。当我使用 ng build 将生产环境中的项目编译为静态部署的文件包时,我收到控制台错误,只有当我使用构建时优化选项为 false 的开发环境时,生成的包才能正常工作。如果我启用优化,尝试该应用程序会产生各种控制台错误。
控制台错误似乎并不一致——看似任意,并且在各个但不是所有组件中。也不可能轻松找出导致错误的原因,这都是因为 main.js 中的对象/函数名称被缩小了。
以下是提到的一些出现的错误:
Error: Uncaught (in promise): TypeError: Cannot read properties of undefined (reading 'resolveComponentFactory')
TypeError: Cannot read properties of undefined (reading 'resolveComponentFactory')
at main.78b92ab8588ccb699d55.js:1:20111326
Error: NG0302: The pipe 'translate' could not be found!
at main.78b92ab8588ccb699d55.js:1:3736300
TypeError: Cannot read properties of undefined (reading 'location')
at gi.injectWindowHeader (main.78b92ab8588ccb699d55.js:1:1439711)
TypeError: Cannot read properties of undefined (reading 'tableColumns')
at ye.ngAfterViewInit (main.78b92ab8588ccb699d55.js:1:19400784)
这是我在 angular.json 中的构建配置:
"configurations": {
"production": {
"budgets": [
{
"type": "anyComponentStyle",
"maximumWarning": "6kb"
},
{
"type": "initial",
"maximumWarning": "2mb"
}
],
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
"outputHashing": "all",
"sourceMap": false,
"namedChunks": false,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true,
"aot": true,
"optimization": {
"scripts": true,
"styles": {
"minify": true,
"inlineCritical": true
}
}
},
"development": {
"vendorChunk": true,
"extractLicenses": false,
"buildOptimizer": false,
"sourceMap": true,
"optimization": false,
"namedChunks": true
}
},
"defaultConfiguration": "development"
},
在构建文件包时禁用优化可以完全解决所有这些问题,并且生成的网站运行良好,没有错误。但是,我不想让我的网站永久处于未优化状态,因为未优化捆绑包的文件大小明显更大,并且优化可能还伴随着各种其他改进。
任何关于为什么优化可能会破坏网站以及如何防止将来发生这种情况的想法,我们将不胜感激。
自行车路线实施没有完美的解决方案。
我看到你的选择是这样的
1:依赖其他东西而不是类名。
例如使用类引用本身(类名被缩小,但对类的引用是相同的)
class AlertComponent {
...
}
...
switch(component.constructor) {
case: AlertComponent: ...;
...
}
2:禁用 mangling,但会增加包大小
"build": "env NG_BUILD_MANGLE=false ng build --prod"