diff --git a/README.md b/README.md index 74d1d293..060b0309 100644 --- a/README.md +++ b/README.md @@ -356,6 +356,23 @@ const miniCssExtractPlugin = new MiniCssExtractPlugin({ For long term caching use `filename: "[contenthash].css"`. Optionally add `[name]`. +#### Determining Insertion Point for Async CSS Chunks + +If you are extracting CSS into separate files and using Webpack Dynamic Imports, it is possible you will need to be able to configure the insertion point of your async CSS chunks in the document to preserve ordering for the CSS cascade. This is possible using the `insertInto` option, which takes a function that will be called to determine the parent node into which to insert the ``` tag for the chunk CSs file + +```javascript +module.exports = { + ... + plugins: [ + new MiniCssExtractPlugin({ + filename: "[name].css", + insertInto: href => document.querySeletor('.async-styles-container'), + }) + ], + ... +} +``` + ### Remove Order Warnings If the terminal is getting bloated with chunk order warnings. You can filter by configuring [warningsFilter](https://webpack.js.org/configuration/stats/) withing the webpack stats option diff --git a/src/index.js b/src/index.js index 0451484d..547986af 100644 --- a/src/index.js +++ b/src/index.js @@ -125,10 +125,13 @@ class MiniCssExtractPlugin { { filename: DEFAULT_FILENAME, moduleFilename: () => options.filename || DEFAULT_FILENAME, + insertInto: null, }, options ); - + if (typeof this.options.insertInto !== 'function') { + throw new Error('insertInto option must be a function'); + } if (!this.options.chunkFilename) { const { filename } = this.options; @@ -362,7 +365,9 @@ class MiniCssExtractPlugin { contentHashType: MODULE_TYPE, } ); - + const insertInto = this.options.insertInto + ? this.options.insertInto.toString() + : 'null'; return Template.asString([ source, '', @@ -418,8 +423,10 @@ class MiniCssExtractPlugin { '}', ]) : '', - 'var head = document.getElementsByTagName("head")[0];', - 'head.appendChild(linkTag);', + `var insertInto = ${insertInto};`, + 'var parent = insertInto ? insertInto(href) : null;', + 'if (parent) { parent.appendChild(linkTag); }', + 'else { document.getElementsByTagName("head")[0].appendChild(linkTag); }', ]), '}).then(function() {', Template.indent(['installedCssChunks[chunkId] = 0;']),