编译后修改文件的webpack插件 [英] Webpack plugin to modify files after compilation
问题描述
我正在编写一个 Webpack 插件,该插件应该用 Webpack 生成的 CSS 文件列表替换部分 JS 代码.对这段 JS 代码进行成像:
I am writing a Webpack plugin that should replace a part of the JS code with a list of Webpack's generated CSS files. Imaging this JS code:
ReactWebComponent.create(<App />, 'react-web-component', { injectReactWebComponent: true });
我想用
injectReactWebComponent: '<link href="static/css/main.cacbacc7.css" rel="stylesheet">'
虽然那个链接标签是由 Webpack 生成的文件.
While that link tag is a file generated by Webpack.
我的(工作)代码如下:
My (kind of working) code for this goes as follows:
ReactWebComponent.prototype.apply = function(compiler) {
compiler.plugin('emit', function(compilation, callback) {
const cssFiles = Object.keys(compilation.assets)
.filter(fileName => /\.css$/.test(fileName));
const jsFiles = Object.keys(compilation.assets)
.filter(fileName => /\.js$/.test(fileName));
const cssLinkTagsAsString = cssFiles
.map(fileName => `<link href="${fileName}" rel="stylesheet">`)
.join('');
jsFiles.forEach(fileName => {
compilation.assets[fileName].children.forEach(child => {
if (child._value) {
child._value = child._value.replace(/injectReactWebComponent\s*:\s*true/g, `injectReactWebComponent: \'${cssLinkTagsAsString}\'`);
}
});
});
callback();
});
};
module.exports = ReactWebComponent;
看我做的那一行
child._value = child._value.replace(...)
我坦率地重写了来源.
但这对我来说似乎不合适.我正在转换的代码似乎已经生成,不应再转换.我也很确定我用这个破坏了源映射.
But this does not seem right for me. It seems the code I am transforming has already been generated and not ought to be transformed anymore. I am also pretty sure I am breaking the source maps with this.
所以我想知道,实现我正在做的事情的合适方法是什么?
So I am wondering, what would be an appropriate way to achieve what I am doing?
我猜测转换部分我应该使用 loader
,但是加载器不知道生成的文件名,或者他们知道吗?
I am guessing for the transformation part I should use a loader
, but then loaders do not know about the generated file names, or do they?
任何帮助将不胜感激!
推荐答案
看起来这种事情很简单,可以由加载器处理,其中有多个(有些比其他更好):
It appears this sort of thing is simple enough to be handled by loaders, of which there are multiple (some better than others):
https://www.npmjs.com/package/string-replace-loader
https://www.npmjs.com/package/regexp-replace-loader
https://www.npmjs.com/package/replace-loader
如果你想制作自己的插件来做到这一点(我只是通过这个过程来做一些比正则表达式替换更复杂的事情),我基本上可以从这三个页面中拼凑出我的解决方案:
If you want to go about making your own plugin to do this (I just went through the process to do something a bit more sophisticated than just regex replacement), I was able to piece my solution together from basically these three pages:
https://github.com/webpack/webpack/blob/master/lib/BannerPlugin.js
https://webpack.js.org/api/plugins/compilation/#optimize-chunk-assets-chunks-chunk-async
https://github.com/webpack/webpack-sources
这篇关于编译后修改文件的webpack插件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!