diff --git a/README.md b/README.md
index 3c570d29..a0f7aa29 100644
--- a/README.md
+++ b/README.md
@@ -343,30 +343,78 @@ module.exports = {
};
```
-#### Module Filename Option
+### Plugin Options
+
+#### moduleFilename
With the `moduleFilename` option you can use chunk data to customize the filename. This is particularly useful when dealing with multiple entry points and wanting to get more control out of the filename for a given entry point/chunk. In the example below, we'll use `moduleFilename` to output the generated css into a different directory.
```javascript
-const miniCssExtractPlugin = new MiniCssExtractPlugin({
+new MiniCssExtractPlugin({
moduleFilename: ({ name }) => `${name.replace('/js/', '/css/')}.css`,
});
```
-#### Long Term Caching
+#### filename
For long term caching use `filename: "[contenthash].css"`. Optionally add `[name]`.
-### Remove Order Warnings
+#### ignoreOrder
+
+Removes order warnings.
For projects where css ordering has been mitigated through consistent use of scoping or naming conventions, the css order warnings can be disabled by setting the ignoreOrder flag to true for the plugin.
```javascript
new MiniCssExtractPlugin({
ignoreOrder: true,
-}),
+});
```
+### insert
+
+Type: `String|Function`
+Default: `head`
+
+By default, the `mini-css-extract-plugin` appends styles (`` elements) to `document.head` of the current `window`.
+
+However in some circumstances it might be necessary to have finer control over the append target or even delay `link` elements instertion. For example this is the case when you asynchronously load styles for an application that runs inside of an iframe. In such cases `insert` can be configured to be a function or a custom selector.
+
+If you target an [iframe](https://developer.mozilla.org/en-US/docs/Web/API/HTMLIFrameElement) make sure that the parent document has sufficient access rights to reach into the frame document and append elements to it.
+
+#### `insert` as a string
+
+Allows to configure a [CSS selector](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector) that will be used to find the element where to append the styles (`link` elements).
+
+```js
+new MiniCssExtractPlugin({
+ insert: '#my-container',
+});
+```
+
+A new `` element will be appended to the `#my-container` element.
+
+#### `insert` as a function
+
+Allows to override default behavior and insert styles at any position.
+
+> ⚠ Do not forget that this code will run in the browser alongside your application. Since not all browsers support latest ECMA features like `let`, `const`, `arrow function expression` and etc we recommend you to use only ECMA 5 features and syntax.
+
+> ⚠ The `insert` function is serialized to string and passed to the plugin. This means that it won't have access to the scope of the webpack configuration module.
+
+```js
+new MiniCssExtractPlugin({
+ insert: function insert(linkTag) {
+ const reference = document.querySelector('#some-element');
+ if (reference) {
+ reference.parentNode.insertBefore(linkTag, reference);
+ }
+ },
+});
+```
+
+A new `` element will be inserted before the element with id `some-element`.
+
### Media Query Plugin
If you'd like to extract the media queries from the extracted CSS (so mobile users don't need to load desktop or tablet specific CSS anymore) you should use one of the following plugins:
diff --git a/src/index.js b/src/index.js
index a21eab13..d77dc1e1 100644
--- a/src/index.js
+++ b/src/index.js
@@ -97,13 +97,23 @@ class CssModuleFactory {
class MiniCssExtractPlugin {
constructor(options = {}) {
+ const insert =
+ typeof options.insert === 'undefined'
+ ? '"head"'
+ : typeof options.insert === 'string'
+ ? JSON.stringify(options.insert)
+ : options.insert.toString();
+
this.options = Object.assign(
{
filename: DEFAULT_FILENAME,
moduleFilename: () => this.options.filename || DEFAULT_FILENAME,
ignoreOrder: false,
},
- options
+ options,
+ {
+ insert,
+ }
);
if (!this.options.chunkFilename) {
@@ -316,6 +326,8 @@ class MiniCssExtractPlugin {
}
);
+ const { insert } = this.options;
+
return Template.asString([
source,
'',
@@ -371,8 +383,9 @@ class MiniCssExtractPlugin {
'}',
])
: '',
- 'var head = document.getElementsByTagName("head")[0];',
- 'head.appendChild(linkTag);',
+ `var insert = ${insert};`,
+ `if (typeof insert === 'function') { insert(linkTag); }`,
+ `else { var target = document.querySelector(${insert}); target && target.appendChild(linkTag); } `,
]),
'}).then(function() {',
Template.indent(['installedCssChunks[chunkId] = 0;']),
diff --git a/src/loader.js b/src/loader.js
index 8e5ac5a5..42d50da8 100644
--- a/src/loader.js
+++ b/src/loader.js
@@ -75,6 +75,7 @@ export function pitch(request) {
: typeof options.publicPath === 'function'
? options.publicPath(this.resourcePath, this.rootContext)
: this._compilation.outputOptions.publicPath;
+
const outputOptions = {
filename: childFilename,
publicPath,
diff --git a/src/options.json b/src/options.json
index 3cc77705..1484f8d6 100644
--- a/src/options.json
+++ b/src/options.json
@@ -10,6 +10,17 @@
"instanceof": "Function"
}
]
+ },
+ "insert": {
+ "description": "Inserts `` at the given position (https://github.com/webpack-contrib/mini-css-extract-plugin#insert).",
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "instanceof": "Function"
+ }
+ ]
}
},
"errorMessages": {
diff --git a/test/cases/insert-function/expected/main.css b/test/cases/insert-function/expected/main.css
new file mode 100644
index 00000000..cebc5c1c
--- /dev/null
+++ b/test/cases/insert-function/expected/main.css
@@ -0,0 +1,4 @@
+body {
+ background: red;
+}
+
diff --git a/test/cases/insert-function/index.js b/test/cases/insert-function/index.js
new file mode 100644
index 00000000..aa3357bf
--- /dev/null
+++ b/test/cases/insert-function/index.js
@@ -0,0 +1 @@
+import './style.css';
diff --git a/test/cases/insert-function/insert-function.test.js b/test/cases/insert-function/insert-function.test.js
new file mode 100644
index 00000000..1dd98ca9
--- /dev/null
+++ b/test/cases/insert-function/insert-function.test.js
@@ -0,0 +1,33 @@
+/* globals document, getComputedStyle */
+
+import path from 'path';
+
+import webpack from 'webpack';
+
+import config from './webpack.config';
+
+describe('options.insert as a function', () => {
+ it('inserts the bundle on the page', (done) => {
+ const outputPath = path.resolve(__dirname, 'expected/index.js');
+ webpack({
+ ...config,
+ output: {
+ path: outputPath,
+ libraryTarget: 'umd',
+ library: 'mini',
+ },
+ }).run(() => {
+ let computedValue = getComputedStyle(document.body).backgroundColor;
+ expect(computedValue).toBe('');
+
+ const script = document.createElement('script');
+ script.src = outputPath;
+ document.head.appendChild(script);
+
+ computedValue = getComputedStyle(document.body).backgroundColor;
+ expect(computedValue).toBe('rgba(0, 0, 0, 0)');
+
+ done();
+ });
+ });
+});
diff --git a/test/cases/insert-function/style.css b/test/cases/insert-function/style.css
new file mode 100644
index 00000000..67ce83e4
--- /dev/null
+++ b/test/cases/insert-function/style.css
@@ -0,0 +1,3 @@
+body {
+ background: red;
+}
diff --git a/test/cases/insert-function/webpack.config.js b/test/cases/insert-function/webpack.config.js
new file mode 100644
index 00000000..e891a7f3
--- /dev/null
+++ b/test/cases/insert-function/webpack.config.js
@@ -0,0 +1,22 @@
+/* globals document */
+import Self from '../../../src';
+
+module.exports = {
+ entry: './index.js',
+ module: {
+ rules: [
+ {
+ test: /\.css$/,
+ use: [Self.loader, 'css-loader'],
+ },
+ ],
+ },
+ plugins: [
+ new Self({
+ filename: '[name].css',
+ insert: function insert(linkTag) {
+ document.head.appendChild(linkTag);
+ },
+ }),
+ ],
+};
diff --git a/test/cases/insert-string/expected/main.css b/test/cases/insert-string/expected/main.css
new file mode 100644
index 00000000..cebc5c1c
--- /dev/null
+++ b/test/cases/insert-string/expected/main.css
@@ -0,0 +1,4 @@
+body {
+ background: red;
+}
+
diff --git a/test/cases/insert-string/index.js b/test/cases/insert-string/index.js
new file mode 100644
index 00000000..aa3357bf
--- /dev/null
+++ b/test/cases/insert-string/index.js
@@ -0,0 +1 @@
+import './style.css';
diff --git a/test/cases/insert-string/style.css b/test/cases/insert-string/style.css
new file mode 100644
index 00000000..67ce83e4
--- /dev/null
+++ b/test/cases/insert-string/style.css
@@ -0,0 +1,3 @@
+body {
+ background: red;
+}
diff --git a/test/cases/insert-string/webpack.config.js b/test/cases/insert-string/webpack.config.js
new file mode 100644
index 00000000..8a40aa99
--- /dev/null
+++ b/test/cases/insert-string/webpack.config.js
@@ -0,0 +1,19 @@
+import Self from '../../../src';
+
+module.exports = {
+ entry: './index.js',
+ module: {
+ rules: [
+ {
+ test: /\.css$/,
+ use: [Self.loader, 'css-loader'],
+ },
+ ],
+ },
+ plugins: [
+ new Self({
+ filename: '[name].css',
+ insert: 'head',
+ }),
+ ],
+};
diff --git a/test/manual/webpack.config.js b/test/manual/webpack.config.js
index 3e511bfa..a8b7847d 100644
--- a/test/manual/webpack.config.js
+++ b/test/manual/webpack.config.js
@@ -1,3 +1,4 @@
+/* globals document */
const Self = require('../../');
module.exports = {
@@ -19,6 +20,9 @@ module.exports = {
new Self({
filename: '[name].css',
chunkFilename: '[contenthash].css',
+ insert: function insert(linkTag) {
+ document.head.appendChild(linkTag);
+ },
}),
],
devServer: {