Angular项目在IE11(开发/生产构建)运行异常求助
嘿,我来帮你搞定这个IE11的报错问题!你遇到的核心问题很明确:IE11完全不支持ES6的箭头函数语法,而全局Angular CLI升到8之后,和你本地Angular 6项目的构建配置出现了兼容性冲突,导致vendor.js里的箭头函数没被转译成IE11能识别的ES5代码。
下面是一步步的解决办法,咱们挨个来试:
1. 先把本地CLI版本和项目对齐
全局CLI和本地项目版本不一致是这类问题的常见诱因,先把本地CLI锁定到和Angular 6匹配的版本:
- 卸载当前本地CLI:
npm uninstall @angular/cli --save-dev - 安装和你项目Angular 6.0.9兼容的6.2.9版本:
npm install @angular/cli@6.2.9 --save-dev - 确认安装成功:
看输出里的本地CLI版本是不是6.2.9,和项目依赖保持一致就对了。ng --version
2. 补全Polyfills配置
你的polyfills.ts已经有了基础配置,但再检查下有没有遗漏的关键项:
打开src/polyfills.ts,确保这些IE11必需的polyfill都被正确引入(注释掉的话就取消注释):
/** IE9, IE10 and IE11 requires all of the following polyfills. **/ import 'core-js/es6/symbol'; import 'core-js/es6/object'; import 'core-js/es6/function'; import 'core-js/es6/parse-int'; import 'core-js/es6/parse-float'; import 'core-js/es6/number'; import 'core-js/es6/math'; import 'core-js/es6/string'; import 'core-js/es6/date'; import 'core-js/es6/array'; import 'core-js/es6/regexp'; import 'core-js/es6/map'; import 'core-js/es6/weak-map'; import 'core-js/es6/set'; /** IE10 and IE11 requires the following for NgClass support on SVG elements */ import 'classlist.js'; /** Evergreen browsers require these. **/ import 'core-js/es6/reflect'; import 'core-js/es7/reflect'; /** Required for Web Animations support */ import 'web-animations-js';
如果你的项目用到了日期、货币这类管道,记得把intl相关的polyfill也加上:
import 'intl'; import 'intl/locale-data/jsonp/en'; // 换成你项目用的语言 locale
3. 确认TypeScript编译目标是ES5
检查tsconfig.json和tsconfig.app.json,确保编译目标设置为ES5,这样TypeScript会把ES6语法转成ES5:
在tsconfig.json的compilerOptions里设置:
{ "compilerOptions": { "target": "es5", "module": "es2015", "moduleResolution": "node", "sourceMap": true, "emitDecoratorMetadata": true, "experimentalDecorators": true, "lib": ["es2017", "dom"], "noImplicitAny": true, "suppressImplicitAnyIndexErrors": true } }
tsconfig.app.json里的target也要保持是es5,别被覆盖了。
4. 调整angular.json的构建配置
打开angular.json,找到你项目的构建配置,确保开启ES5兼容:
在projects -> edmw-project -> architect -> build -> options里添加或确认:
"options": { "target": "es5", "aot": true, // 保留你原来的其他配置 }
开发环境的serve配置(architect -> serve -> options)也做同样检查,确保target是es5。
5. 清缓存重新构建
缓存经常会搞事情,咱们把旧缓存清干净再重新来:
- 清除npm缓存:
npm cache clean --force - 删除
node_modules和package-lock.json:rm -rf node_modules package-lock.json - 重新安装依赖:
npm install - 重新构建生产版本:
ng build --prod - 本地开发服务也重启:
ng serve --port 4300 --proxy-config proxy.conf.json
验证结果
做完这些步骤后,打开IE11重新加载项目,然后去vendor.js里找那个isPresent函数,如果它变成了ES5的普通函数:
function isPresent(value) { return value !== null && value !== undefined; }
那说明转译成功了,报错应该就消失啦!
内容的提问来源于stack exchange,提问作者Amit

