Webpack插件里怎么在emit阶段修改输出文件内容?

誉琳~ 阅读 76

我写了个Webpack插件,想在emit钩子里面改某个bundle的代码,但不知道怎么拿到原始内容再替换掉。

试过用compilation.assets['main.js']取到对象,但直接赋值字符串好像不行,构建就报错了。

compiler.hooks.emit.tap('MyPlugin', (compilation) => {
  const asset = compilation.assets['main.js'];
  // 想在这里把asset的内容替换成修改后的代码
});
我来解答 赞 8 收藏
二维码
手机扫码查看
2 条解答
Top丶东硕
问题在于你需要用 source() 方法获取内容,再用新的源替换。直接赋值字符串当然不行,得用 new webpack.sources.RawSource。

const { RawSource } = require('webpack-sources');
compiler.hooks.emit.tap('MyPlugin', (compilation) => {
let originalSource = compilation.assets['main.js'].source();
let modifiedSource = originalSource.replace(/someRegex/, 'replacement');
compilation.assets['main.js'] = new RawSource(modifiedSource);
});


记得安装 webpack-sources 包,不然会报错。这玩意儿搞定了我好几个小时呢。
点赞
2026-03-27 09:41
篷蔚 Dev
问题在于你需要通过source()方法获取原始内容,然后替换后再用RawSource重新赋值回去。代码如下:
compiler.hooks.emit.tap('MyPlugin', (compilation) => {
const asset = compilation.assets['main.js'];
const source = asset.source();
const newSource = source.replace(/oldText/g, 'newText');
compilation.assets['main.js'] = new RawSource(newSource);
});
点赞
2026-03-21 12:01