Skip to content

Add support for the insert option #459

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 53 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 (`<link>` 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 `<link>` 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 `<link>` 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:
Expand Down
19 changes: 16 additions & 3 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -316,6 +326,8 @@ class MiniCssExtractPlugin {
}
);

const { insert } = this.options;

return Template.asString([
source,
'',
Expand Down Expand Up @@ -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;']),
Expand Down
1 change: 1 addition & 0 deletions src/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
11 changes: 11 additions & 0 deletions src/options.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,17 @@
"instanceof": "Function"
}
]
},
"insert": {
"description": "Inserts `<link>` at the given position (https://github.com/webpack-contrib/mini-css-extract-plugin#insert).",
"anyOf": [
{
"type": "string"
},
{
"instanceof": "Function"
}
]
}
},
"errorMessages": {
Expand Down
4 changes: 4 additions & 0 deletions test/cases/insert-function/expected/main.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
body {
background: red;
}

1 change: 1 addition & 0 deletions test/cases/insert-function/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
import './style.css';
33 changes: 33 additions & 0 deletions test/cases/insert-function/insert-function.test.js
Original file line number Diff line number Diff line change
@@ -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;
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@evilebottnawi it seems that webpack is not emitting this file and it 404s. Also I am not sure jsdom supports getComputedStyle. In that case I think we either get rid of this test or need to set up something like Puppeteer which IMO is out of scope.

document.head.appendChild(script);

computedValue = getComputedStyle(document.body).backgroundColor;
expect(computedValue).toBe('rgba(0, 0, 0, 0)');

done();
});
});
});
3 changes: 3 additions & 0 deletions test/cases/insert-function/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
body {
background: red;
}
22 changes: 22 additions & 0 deletions test/cases/insert-function/webpack.config.js
Original file line number Diff line number Diff line change
@@ -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);
},
}),
],
};
4 changes: 4 additions & 0 deletions test/cases/insert-string/expected/main.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
body {
background: red;
}

1 change: 1 addition & 0 deletions test/cases/insert-string/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
import './style.css';
3 changes: 3 additions & 0 deletions test/cases/insert-string/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
body {
background: red;
}
19 changes: 19 additions & 0 deletions test/cases/insert-string/webpack.config.js
Original file line number Diff line number Diff line change
@@ -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',
}),
],
};
4 changes: 4 additions & 0 deletions test/manual/webpack.config.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* globals document */
const Self = require('../../');

module.exports = {
Expand All @@ -19,6 +20,9 @@ module.exports = {
new Self({
filename: '[name].css',
chunkFilename: '[contenthash].css',
insert: function insert(linkTag) {
document.head.appendChild(linkTag);
},
}),
],
devServer: {
Expand Down