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;