Angular 6自定义元素在IE11及Firefox中因语法与Shadow DOM报错
我之前遇到过完全一样的坑,根源其实很明确:@webcomponents/custom-elements的源码文件(比如你提到的native-shim.js)里包含IE11不支持的ES6箭头函数,而Angular CLI默认不会转译node_modules目录下的文件,直接引入就会触发语法报错。下面是我亲测有效的解决方案:
1. 替换polyfills中的@webcomponents引入路径
别再直接引入源码目录下的native-shim.js了,改用官方预编译好的ES5兼容版本。先确保安装了完整的webcomponents polyfill包:
npm install --save @webcomponents/webcomponentsjs
然后修改src/polyfills.ts,替换掉原来的@webcomponents相关引入:
// 移除这两行有问题的引入 // import '@webcomponents/custom-elements/custom-elements.min'; // import '@webcomponents/custom-elements/src/native-shim'; // 换成官方预编译的ES5兼容版本 import '@webcomponents/webcomponentsjs/webcomponents-bundle.js'; import '@webcomponents/webcomponentsjs/custom-elements-es5-adapter.js';
webcomponents-bundle.js包含了所有必要的webcomponents polyfills,且已经转译为ES5;custom-elements-es5-adapter.js专门处理ES5环境下自定义元素的适配问题,完美解决箭头函数这类语法兼容问题。
2. 配置Angular CLI确保ES5兼容与依赖处理
由于@webcomponents的包是CommonJS格式,需要在angular.json中做配置,避免构建警告同时确保IE11能正常解析:
找到projects -> [你的项目名] -> architect -> build -> options,添加以下配置:
"options": { // ...保留你原有的其他配置 "target": "es5", "es5BrowserSupport": true, "allowedCommonJsDependencies": [ "@webcomponents/webcomponentsjs", "@webcomponents/custom-elements" ] }
同时检查tsconfig.json的compilerOptions.target是否设置为es5,确保整个项目的编译目标是ES5:
"compilerOptions": { "target": "es5", // ...其他配置 }
3. 验证构建与运行
执行生产构建命令:
ng build --prod
把构建后的文件部署到服务器,在IE11中测试即可。如果还有问题,可以试试这两个额外调整:
- 确认
polyfills.ts中所有IE11需要的polyfills都已启用(你当前的配置已经覆盖了大部分核心的core-js模块,没问题) - 如果使用Angular 9+,可以尝试禁用Ivy编译器,在
tsconfig.json中添加:
"angularCompilerOptions": { "enableIvy": false }
额外优化:条件加载polyfills
为了不影响现代浏览器的加载速度,可以在index.html中用IE条件注释,只在IE环境下加载webcomponents polyfills:
<!--[if IE]> <script src="node_modules/@webcomponents/webcomponentsjs/webcomponents-bundle.js"></script> <script src="node_modules/@webcomponents/webcomponentsjs/custom-elements-es5-adapter.js"></script> <![endif]-->
同时记得移除polyfills.ts中的对应引入,这样Chrome、Firefox这类现代浏览器就不会加载冗余的polyfills了。
我用这套配置搭建的Angular Elements项目完全能在IE11中正常运行,你可以照着调整你的项目试试。
内容的提问来源于stack exchange,提问作者Jim

