我正在编写一个Webpack插件,它应该用Webpack生成的CSS文件列表来替换JS代码的一部分。想象一下这段JS代码:
ReactWebComponent.create(<App />, 'react-web-component', { injectReactWebComponent: true });
我希望用其他内容代替 injectReactWebComponent: true
部分。
injectReactWebComponent: '<link href="static/css/main.cacbacc7.css" rel="stylesheet">'
虽然那个链接标签是由Webpack生成的文件。
我(有点能用)的代码如下:
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(...)
我直截了当地重写源代码。
但是这对我来说似乎不太对。看起来我正在转换的代码已经被生成,不应再进行转换。 我也很确定我正在破坏源映射。
因此,我想知道,达成我的目标的合适方法是什么?
我猜转换部分应该使用一个loader
,但是加载器不知道生成的文件名,对吗?
任何帮助将不胜感激!