I'm working on a Webpack plugin that basically looks for a css
assets inside the chunks, when it founds such asset, applies on it some postCSS
plugin that returns 2 outputs, the one should continue to be extracted using Extract-Text-Plugin
and the other output should become a new module inside the chunk that injects it to the head on runtime.
The only part that I'm not managed to implement is the part that creates a new module inside existing Chunk. There is some pointers / ideas?
I managed to create a new chunk out of it but without webpack wrappers, that means that I'm not able to support HMR for that piece of css and load it lazily.
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;
result.extracted
(this style should be injected into an inline style) will become a webpack module inside the original Chunk. – Classicextract-text-plugin
, and next part intostyle-loader
(which will render it to HTML head). Correct? – Ferine