I am working on a Webpack plugin that basically searches for css assets inside pieces, when it detects such an asset, applies some postCSS plugin to it that returns 2 outputs, it should continue to be extracted using Extract-Text-Plugin , and the other output should become new module inside the fragment , which introduces it to the beginning at runtime.
The only part that I could not implement is the part that creates a new module inside the existing Chunk. Got a few pointers / ideas?
I managed to create a new fragment , but without webpack env, this means that I cannot support HMR for this css fragment.
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;
source share