webpack 打包时修改源码

更新于 阅读 23

由于需要在代码编译的时候动态修改代码,所以通过插件的方式实现,代码如下:

const webpack = require("webpack"); const ConcatSource = require("webpack-sources").ConcatSource; class CustomPlugin { constructor(options) {} apply(compiler) { compiler.hooks.compilation.tap("CustomPlugin", (compilation) => { compilation.hooks.processAssets.tapAsync( { name: "CustomPlugin", stage: webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE, additionalAssets: true, }, (assets, callback) => { Object.entries(assets).forEach(([pathname, source]) => { // 找到对应的文件 if (pathname === "app.js") { let input = source.source().replace("//@code-anchor", '"你好"'); assets[pathname] = new ConcatSource(input); } }); callback(); } ); }); } } module.exports = CustomPlugin;