我正在尝试编写一个Webpack插件,它接受webpack生成的CSS并为其添加自定义前缀。我已经启动并运行并连接到编译器的emit
阶段,但我无法找到一种优雅的方式来访问我需要的文件内容。
以下是我到目前为止所获得的所有代码,基于示例Writing a Plugin。如何访问资产的内容?记录compilation.assets['main.css']
仅显示对源的脏访问。
PrefixCssPlugin.prototype.apply = function(compiler) {
compiler.plugin('after-compile', function(compilation) {
console.log(new RawSource(compilation.assets['main.css']));
});
compiler.plugin('emit', (compilation, callback) => {
let prefixedCssContent = '';
for (const filename in compilation.assets) {
for (const pattern in filePatterns) {
if (filePatterns[pattern].test(filename)) {
console.log(`${filename} matched ${filePatterns[pattern]}`);
console.log(JSON.stringify(compilation.assets[filename]));
// I want to access the contents of the matched file here, and pass it
// to another module that will handle the prefixing.
/* prefixedCssContent = cssPrefixer(
compilation.assets[filename],
cssPrefix,
shouldPrefixElements); */
}
}
}
// Insert this list into the webpack build as a new file asset:
compilation.assets['prefixed.css'] = {
source: function() {
return prefixedCssContent;
},
size: function() {
return prefixedCssContent.length
}
};
callback();
});
};