script-ext-html-webpack-plugin webpack插件做监控插入

本文介绍了如何在webpack配置文件中使用script-ext-html-webpack-plugin插件来为动态生成的script标签添加属性,如crossorigin,并提供了针对html-webpack-plugin版本限制的解决方案及自定义插件实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

script-ext-html-webpack-plugin的使用

在webpack.config.js中使用

const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin');

new ScriptExtHtmlWebpackPlugin({

custom: {

test: /\.js$/,

attribute: 'crossorigin',

value: 'anonymous',

},

}),

output: {

path: paths.appBuild,

crossOriginLoading: 'anonymous',

},

必须要保证 html-webpack-plugin的版本为4.5.0版本 不能升级到5.5.0版本及以上 npm list html-webpack-plugin版本不一致时,会导致script-ext-html-webpack-plugin插件不可用,主要是源码中HtmlWebpackPlugin.getHooks(compilation).alterAssetTags.tapAsync不存在 不会执行

下面是手写的一个plugin -解决动态script标签增加属性的功能:

const HtmlWebpackPlugin = require('html-webpack-plugin');

class CrossOriginPlugin {

apply(compiler) {

compiler.hooks.compilation.tap('CrossOriginPlugin', (compilation) => {

console.log(1111)

HtmlWebpackPlugin.getHooks(compilation).alterAssetTags.tapAsync(

'CrossOriginPlugin',

(data, callback) => {

console.log(222222)

data.assetTags.scripts.forEach(script => {

if (script.tagName === 'script' && script.attributes) {

script.attributes.crossorigin = 'anonymous';

}

});

if (callback) {

callback(null, data);

}

}

);

});

}

}

module.exports = CrossOriginPlugin;

### 配置 `script-ext-html-webpack-plugin` 插件 为了增强 HTML 文件中脚本标签的功能,在 Webpack 5 中可以使用 `script-ext-html-webpack-plugin` 来实现更灵活的部署选项。此插件扩展了 `html-webpack-plugin` 的功能,允许开发者通过不同的属性来优化资源加载方式。 #### 安装必要的依赖包 首先需要确保已经安装了 `html-webpack-plugin` 和 `script-ext-html-webpack-plugin`: ```bash npm install html-webpack-plugin script-ext-html-webpack-plugin --save-dev ``` 这段命令会将这两个插件作为开发环境下的依赖项加入到项目当中[^1]。 #### 修改 Webpack 配置文件 接着修改 `webpack.config.js` 文件以引入这些插件,并对其进行适当配置: ```javascript const HtmlWebpackPlugin = require('html-webpack-plugin'); const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin'); module.exports = { // ...其他配置... plugins: [ new HtmlWebpackPlugin({ template: './public/index.html', filename: 'index.html' }), new ScriptExtHtmlWebpackPlugin({ defaultAttribute: 'async' // 设置默认属性为异步加载 }) ] }; ``` 上述代码片段展示了如何利用 `ScriptExtHtmlWebpackPluging` 对所有注入的 `<script>` 标签添加特定属性(此处设定了 `async` 属性),从而改善页面性能[^2]。 对于希望针对单个 JavaScript 资源应用不同策略的情况,则可以在 `html-webpack-plugin` 的模板内手动指定所需的属性;而当涉及到多个入口点时,也可以借助于该插件提供的 API 实现更加复杂的场景定制化需求[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值