我正在开发一个Webpack插件,它基本上是在块内寻找一个css资产,当它创建这样的资产时,在它上应用一些返回两个输出的postCSS插件,一个应该继续使用Extract-Text-Plugin提取,另一个输出应该成为块中的一个新模块,在运行时将其注入头部。
我无法实现的唯一部分是在现有的块中创建一个新模块的部分。有一些建议/想法吗?
我成功地用它创建了一个新块,但是没有webpack包装器,这意味着我不能为这段css支持HMR,并且懒洋洋地加载它。
class ExtractTPAStylePlugin {
constructor(options) {
this._options = Object.assign({
pattern: [
/"\w+\([^\)]+\)"/
]
}, options);
}
extract(compilation, chunks) {
const promises = [];
chunks.forEach((chunk) => {
promises.push(
chunk.files
.filter(fileName => fileName.endsWith('.css'))
.map(file => postcss([extractStyles(this._options)])
.process(compilation.assets[file].source(), {from: file, to: file})
.then((result) => {
compilation.assets[file] = new RawSource(result.css);
const filename = file.replace('.css', fileSuffix);
const newChunk = new Chunk(filename);
newChunk.files = [filename];
newChunk.ids = [];
compilation.chunks.push(newChunk);
const extractedStyles = `(${addStylesTemplate})()`
.replace('__CSS__', JSON.stringify(result.extracted))
.replace('__ID__', file);
compilation.assets[filename] = new OriginalSource(extractedStyles);
}))
);
});
return Promise.all(promises);
}
apply(compiler) {
compiler.plugin('compilation', (compilation) => {
compilation.plugin('optimize-chunk-assets', (chunks, callback) => {
this.extract(compilation, chunks)
.then(() => callback())
.catch(callback);
});
});
}
}
module.exports = ExtractTPAStylePlugin;发布于 2018-08-12 19:25:40
好的,我已经从几个插件中收集了一些代码,成功的解决方案是将一个加载器插入到某个假导入文件中,在加载器将整个js代码加载到主包中,并为optimize-chunk-assets阶段的结果放置一些占位符。
之后,在optimize-chunk-assets中,您可以找到相关的块,并使用ReplaceSource查找和替换占位符。
为了获得灵感,您可以查看一下插件。
发布于 2019-03-24 14:06:19
也许有更多的方法可以做到这一点。
我发现的一种方便的方法是创建一个定制的NormalModuleFactory插件并将其与编译器挂钩。
插件接收模块请求和上下文(导入的内容在哪里)。这样,您就可以匹配请求并返回模块源。简化后,它看起来类似于:
class CustomModuleFactoryPlugin {
apply (normalModuleFactory) {
// Tap in the factory hook.
normalModuleFactory.hooks.factory.tap(
'CustomModuleFactoryPlugin',
factory => (data, cb) => {
const { context } = data
const { request } = data.dependencies[0]
if (path.join(context, request).contains('/something/you/expect') {
return cb(null, new RawSource('Success!'))
}
return factory(data, cb)
}
)
}
}https://stackoverflow.com/questions/49088183
复制相似问题