欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 家装 > webpack插件给所有的:src文件目录增加前缀

webpack插件给所有的:src文件目录增加前缀

2024/10/24 9:29:00 来源:https://blog.csdn.net/dongheng123/article/details/140679773  浏览:    关键词:webpack插件给所有的:src文件目录增加前缀

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完成,感慨能力之强大啊

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com