1.webpack4的版本写法
class AddPrefixPlugin {
apply(compiler) {
compiler.hooks.compilation.tap('AddPrefixPlugin', (compilation) => {
HtmlWebpackPlugin.getHooks(compilation).beforeEmit.tapAsync(
'AddPrefixPlugin',
(data, cb) => {
// 使用正则表达式替换所有包含 /static/file/ 的路径
data.html = data.html.replace(/\/static\/file\//g, '/zhgdxmf/static/file/');
cb(null, data);
}
);
});
compiler.hooks.emit.tapAsync('AddPrefixPlugin', (compilation, callback) => {
// 遍历所有输出的资源文件,替换其中的 /static/file/ 路径
Object.keys(compilation.assets).forEach((assetName) => {
if (assetName.endsWith('.js') || assetName.endsWith('.html')) {
let content = compilation.assets[assetName].source();
content = content.replace(/\/static\/file\//g, '/zhgdxmf/static/file/');
compilation.assets[assetName] = {
source: () => content,
size: () => content.length
};
}
});
callback();
});
}
}
module.exports = AddPrefixPlugin;
webpack 2 的版本
function AddPrefixPlugin(options) {
this.options = options || {};
}
AddPrefixPlugin.prototype.apply = function(compiler) {
compiler.plugin('compilation', (compilation) => {
compilation.plugin('html-webpack-plugin-before-html-processing', (htmlPluginData, callback) => {
// 使用正则表达式替换所有包含 /static/file/ 的路径
htmlPluginData.html = htmlPluginData.html.replace(/\/static\/file\//g, '/zhgdxmf/static/file/');
callback(null, htmlPluginData);
});
compilation.plugin('optimize-assets', (assets, callback) => {
// 遍历所有输出文件,替换其中的 /static/file/ 路径
Object.keys(assets).forEach((assetName) => {
if (assetName.endsWith('.js') || assetName.endsWith('.html')) {
let content = assets[assetName].source();
content = content.replace(/\/static\/file\//g, '/zhgdxmf/static/file/');
assets[assetName] = {
source: () => content,
size: () => content.length
};
}
});
callback();
});
});
};
module.exports = AddPrefixPlugin;
使用
全程借助chatgpt完成,感慨能力之强大啊