如何配置angular.json让第三方脚本以type="module"加载?
Angular 第三方脚本以
type="module"引入的解决方案 目前通过angular.json的"scripts"数组配置第三方脚本,无法直接让生成的<script>标签带上type="module"属性,官方文档也未提供相关配置项。以下是几种可行的最佳实践方案:
1. 手动在index.html中引入
直接在项目根目录的index.html里手动添加带type="module"的脚本标签:
<script src="node_modules/third-part/script.js" type="module"></script>
若要适配生产构建,需将第三方脚本拷贝到输出目录,可在angular.json的"assets"数组中添加配置:
"assets": [ "src/favicon.ico", "src/assets", { "glob": "script.js", "input": "node_modules/third-part/", "output": "./assets/third-part/" } ]
之后修改index.html中的引用路径:
<script src="/assets/third-part/script.js" type="module"></script>
2. 组件内动态加载脚本
在需要用到脚本的组件中,通过代码动态创建<script>标签并设置type="module",比如在ngOnInit钩子中:
import { OnInit } from '@angular/core'; export class YourComponent implements OnInit { ngOnInit(): void { const scriptElement = document.createElement('script'); scriptElement.src = '/assets/third-part/script.js'; scriptElement.type = 'module'; document.body.appendChild(scriptElement); } }
这种方式可以按需加载脚本,避免不必要的资源加载。
3. 自定义Webpack配置扩展
借助自定义Webpack配置和插件实现自动添加type="module"属性:
- 安装依赖:
npm install @angular-builders/custom-webpack script-ext-html-webpack-plugin --save-dev
- 修改
angular.json的构建配置,切换为自定义Webpack builder:
"architect": { "build": { "builder": "@angular-builders/custom-webpack:browser", "options": { "customWebpackConfig": { "path": "./webpack.config.js" }, // 保留原有其他配置项 } } }
- 在项目根目录创建
webpack.config.js:
const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin'); module.exports = { plugins: [ new ScriptExtHtmlWebpackPlugin({ module: ['script.js'] // 指定需要设置为module的脚本文件名 }) ] };
内容的提问来源于stack exchange,提问作者Tim
相关产品推荐
相关产品推荐

