diff --git a/README.md b/README.md index f072fc05..5c3a37a2 100644 --- a/README.md +++ b/README.md @@ -96,6 +96,14 @@ module.exports = { // both options are optional filename: devMode ? '[name].css' : '[name].[hash].css', chunkFilename: devMode ? '[id].css' : '[id].[hash].css', + // optional callback allows post-processing of the modules produced by the plugin. `modules` is a Set in the + // final output order; you can mutate the set, or return a new set. `chunk.name` provides the name of the chunk + onEmit: function(chunk, modules) { + if (chunk.name === 'some-chunk') { + return processModules(modules); + } + }, + }), }) ], module: { diff --git a/src/index.js b/src/index.js index 3e2a9001..ae65cfd5 100644 --- a/src/index.js +++ b/src/index.js @@ -500,6 +500,14 @@ class MiniCssExtractPlugin { modules.sort((a, b) => a.index2 - b.index2); usedModules = modules; } + + if (this.options.onEmit) { + const replaced = this.options.onEmit(chunk, usedModules); + if (replaced) { + usedModules = replaced; + } + } + const source = new ConcatSource(); const externalsSource = new ConcatSource(); for (const m of usedModules) { diff --git a/test/cases/on-emit/a.css b/test/cases/on-emit/a.css new file mode 100644 index 00000000..31fc5b8a --- /dev/null +++ b/test/cases/on-emit/a.css @@ -0,0 +1 @@ +body { background: red; } diff --git a/test/cases/on-emit/b.css b/test/cases/on-emit/b.css new file mode 100644 index 00000000..56af6df5 --- /dev/null +++ b/test/cases/on-emit/b.css @@ -0,0 +1 @@ +body { background: green; } diff --git a/test/cases/on-emit/expected/main.css b/test/cases/on-emit/expected/main.css new file mode 100644 index 00000000..f49bc882 --- /dev/null +++ b/test/cases/on-emit/expected/main.css @@ -0,0 +1,4 @@ +body { background: green; } + +body { background: red; } + diff --git a/test/cases/on-emit/index.js b/test/cases/on-emit/index.js new file mode 100644 index 00000000..a0ec7954 --- /dev/null +++ b/test/cases/on-emit/index.js @@ -0,0 +1,2 @@ +import './a.css'; +import './b.css'; diff --git a/test/cases/on-emit/webpack.config.js b/test/cases/on-emit/webpack.config.js new file mode 100644 index 00000000..0571ad0e --- /dev/null +++ b/test/cases/on-emit/webpack.config.js @@ -0,0 +1,24 @@ +const Self = require('../../../'); + +module.exports = { + entry: './index.js', + module: { + rules: [ + { + test: /\.css$/, + use: [Self.loader, 'css-loader'], + }, + ], + }, + plugins: [ + new Self({ + filename: '[name].css', + onEmit: function(chunk, modules) { + if (chunk.name !== 'main') { + throw new Error('Chunk object was not passed correctly'); + } + return new Set(Array.from(modules).reverse()); + }, + }), + ], +};