mini-css-extract-plugin
Advanced tools
Comparing version 1.0.0 to 1.1.0
@@ -5,2 +5,16 @@ # Changelog | ||
## [1.1.0](https://github.com/webpack-contrib/mini-css-extract-plugin/compare/v1.0.0...v1.1.0) (2020-10-19) | ||
### Features | ||
* added the `attributes` option ([e8a2d5a](https://github.com/webpack-contrib/mini-css-extract-plugin/commit/e8a2d5a09ded967e0f4be145f1f52c1e5f7f6df1)) | ||
* added the `insert` option ([a5f17c4](https://github.com/webpack-contrib/mini-css-extract-plugin/commit/a5f17c48cbf0c198ebc955032d11593434ef2373)) | ||
### Bug Fixes | ||
* ignore modules without identifier ([#627](https://github.com/webpack-contrib/mini-css-extract-plugin/issues/627)) ([71a9ce9](https://github.com/webpack-contrib/mini-css-extract-plugin/commit/71a9ce91b377fff892068b87445372fe1c2db142)) | ||
* remove `normalize-url` from deps ([#623](https://github.com/webpack-contrib/mini-css-extract-plugin/issues/623)) ([9ae47e5](https://github.com/webpack-contrib/mini-css-extract-plugin/commit/9ae47e51f198f2e0258d0e87d6e708e57c05bf86)) | ||
### [1.0.0](https://github.com/webpack-contrib/mini-css-extract-plugin/compare/v0.12.0...v1.0.0) (2020-10-09) | ||
@@ -7,0 +21,0 @@ |
@@ -34,5 +34,6 @@ "use strict"; | ||
module.exports = class CssLoadingRuntimeModule extends _webpack.RuntimeModule { | ||
constructor(runtimeRequirements) { | ||
constructor(runtimeRequirements, runtimeOptions) { | ||
super('css loading', 10); | ||
this.runtimeRequirements = runtimeRequirements; | ||
this.runtimeOptions = runtimeOptions; | ||
} | ||
@@ -56,5 +57,5 @@ | ||
if (!withLoading && !withHmr) return null; | ||
return _webpack.Template.asString([`var createStylesheet = ${runtimeTemplate.basicFunction('fullhref, resolve, reject', ['var linkTag = document.createElement("link");', 'linkTag.rel = "stylesheet";', 'linkTag.type = "text/css";', 'linkTag.onload = resolve;', 'linkTag.onerror = function(event) {', _webpack.Template.indent(['var request = event && event.target && event.target.src || fullhref;', 'var err = new Error("Loading CSS chunk " + chunkId + " failed.\\n(" + request + ")");', 'err.code = "CSS_CHUNK_LOAD_FAILED";', 'err.request = request;', 'linkTag.parentNode.removeChild(linkTag)', 'reject(err);']), '};', 'linkTag.href = fullhref;', crossOriginLoading ? _webpack.Template.asString([`if (linkTag.href.indexOf(window.location.origin + '/') !== 0) {`, _webpack.Template.indent(`linkTag.crossOrigin = ${JSON.stringify(crossOriginLoading)};`), '}']) : '', 'var head = document.getElementsByTagName("head")[0];', 'head.appendChild(linkTag);', 'return linkTag;'])};`, `var findStylesheet = ${runtimeTemplate.basicFunction('href, fullhref', ['var existingLinkTags = document.getElementsByTagName("link");', 'for(var i = 0; i < existingLinkTags.length; i++) {', _webpack.Template.indent(['var tag = existingLinkTags[i];', 'var dataHref = tag.getAttribute("data-href") || tag.getAttribute("href");', 'if(tag.rel === "stylesheet" && (dataHref === href || dataHref === fullhref)) return tag;']), '}', 'var existingStyleTags = document.getElementsByTagName("style");', 'for(var i = 0; i < existingStyleTags.length; i++) {', _webpack.Template.indent(['var tag = existingStyleTags[i];', 'var dataHref = tag.getAttribute("data-href");', 'if(dataHref === href || dataHref === fullhref) return tag;']), '}'])};`, `var loadStylesheet = ${runtimeTemplate.basicFunction('chunkId', `return new Promise(${runtimeTemplate.basicFunction('resolve, reject', [`var href = ${_webpack.RuntimeGlobals.require}.miniCssF(chunkId);`, `var fullhref = ${_webpack.RuntimeGlobals.publicPath} + href;`, 'if(findStylesheet(href, fullhref)) return resolve();', 'createStylesheet(fullhref, resolve, reject);'])});`)}`, withLoading ? _webpack.Template.asString(['// object to store loaded CSS chunks', 'var installedCssChunks = {', _webpack.Template.indent(chunk.ids.map(id => `${JSON.stringify(id)}: 0`).join(',\n')), '};', '', `${_webpack.RuntimeGlobals.ensureChunkHandlers}.miniCss = ${runtimeTemplate.basicFunction('chunkId, promises', [`var cssChunks = ${JSON.stringify(chunkMap)};`, 'if(installedCssChunks[chunkId]) promises.push(installedCssChunks[chunkId]);', 'else if(installedCssChunks[chunkId] !== 0 && cssChunks[chunkId]) {', _webpack.Template.indent([`promises.push(installedCssChunks[chunkId] = loadStylesheet(chunkId).then(${runtimeTemplate.basicFunction('', 'installedCssChunks[chunkId] = 0;')}, ${runtimeTemplate.basicFunction('e', ['delete installedCssChunks[chunkId];', 'throw e;'])}));`]), '}'])};`]) : '// no chunk loading', '', withHmr ? _webpack.Template.asString(['var oldTags = [];', 'var newTags = [];', `var applyHandler = ${runtimeTemplate.basicFunction('options', [`return { dispose: ${runtimeTemplate.basicFunction('', ['for(var i = 0; i < oldTags.length; i++) {', _webpack.Template.indent(['var oldTag = oldTags[i];', 'if(oldTag.parentNode) oldTag.parentNode.removeChild(oldTag);']), '}', 'oldTags.length = 0;'])}, apply: ${runtimeTemplate.basicFunction('', ['for(var i = 0; i < newTags.length; i++) newTags[i].rel = "stylesheet";', 'newTags.length = 0;'])} };`])}`, `${_webpack.RuntimeGlobals.hmrDownloadUpdateHandlers}.miniCss = ${runtimeTemplate.basicFunction('chunkIds, removedChunks, removedModules, promises, applyHandlers, updatedModulesList', ['applyHandlers.push(applyHandler);', `chunkIds.forEach(${runtimeTemplate.basicFunction('chunkId', [`var href = ${_webpack.RuntimeGlobals.require}.miniCssF(chunkId);`, `var fullhref = ${_webpack.RuntimeGlobals.publicPath} + href;`, 'const oldTag = findStylesheet(href, fullhref);', 'if(!oldTag) return;', `promises.push(new Promise(${runtimeTemplate.basicFunction('resolve, reject', [`var tag = createStylesheet(fullhref, ${runtimeTemplate.basicFunction('', ['tag.as = "style";', 'tag.rel = "preload";', 'resolve();'])}, reject);`, 'oldTags.push(oldTag);', 'newTags.push(tag);'])}));`])});`])}`]) : '// no hmr']); | ||
return _webpack.Template.asString([`var createStylesheet = ${runtimeTemplate.basicFunction('fullhref, resolve, reject', ['var linkTag = document.createElement("link");', this.runtimeOptions.attributes, 'linkTag.rel = "stylesheet";', 'linkTag.type = "text/css";', 'linkTag.onload = resolve;', 'linkTag.onerror = function(event) {', _webpack.Template.indent(['var request = event && event.target && event.target.src || fullhref;', 'var err = new Error("Loading CSS chunk " + chunkId + " failed.\\n(" + request + ")");', 'err.code = "CSS_CHUNK_LOAD_FAILED";', 'err.request = request;', 'linkTag.parentNode.removeChild(linkTag)', 'reject(err);']), '};', 'linkTag.href = fullhref;', crossOriginLoading ? _webpack.Template.asString([`if (linkTag.href.indexOf(window.location.origin + '/') !== 0) {`, _webpack.Template.indent(`linkTag.crossOrigin = ${JSON.stringify(crossOriginLoading)};`), '}']) : '', this.runtimeOptions.insert, 'return linkTag;'])};`, `var findStylesheet = ${runtimeTemplate.basicFunction('href, fullhref', ['var existingLinkTags = document.getElementsByTagName("link");', 'for(var i = 0; i < existingLinkTags.length; i++) {', _webpack.Template.indent(['var tag = existingLinkTags[i];', 'var dataHref = tag.getAttribute("data-href") || tag.getAttribute("href");', 'if(tag.rel === "stylesheet" && (dataHref === href || dataHref === fullhref)) return tag;']), '}', 'var existingStyleTags = document.getElementsByTagName("style");', 'for(var i = 0; i < existingStyleTags.length; i++) {', _webpack.Template.indent(['var tag = existingStyleTags[i];', 'var dataHref = tag.getAttribute("data-href");', 'if(dataHref === href || dataHref === fullhref) return tag;']), '}'])};`, `var loadStylesheet = ${runtimeTemplate.basicFunction('chunkId', `return new Promise(${runtimeTemplate.basicFunction('resolve, reject', [`var href = ${_webpack.RuntimeGlobals.require}.miniCssF(chunkId);`, `var fullhref = ${_webpack.RuntimeGlobals.publicPath} + href;`, 'if(findStylesheet(href, fullhref)) return resolve();', 'createStylesheet(fullhref, resolve, reject);'])});`)}`, withLoading ? _webpack.Template.asString(['// object to store loaded CSS chunks', 'var installedCssChunks = {', _webpack.Template.indent(chunk.ids.map(id => `${JSON.stringify(id)}: 0`).join(',\n')), '};', '', `${_webpack.RuntimeGlobals.ensureChunkHandlers}.miniCss = ${runtimeTemplate.basicFunction('chunkId, promises', [`var cssChunks = ${JSON.stringify(chunkMap)};`, 'if(installedCssChunks[chunkId]) promises.push(installedCssChunks[chunkId]);', 'else if(installedCssChunks[chunkId] !== 0 && cssChunks[chunkId]) {', _webpack.Template.indent([`promises.push(installedCssChunks[chunkId] = loadStylesheet(chunkId).then(${runtimeTemplate.basicFunction('', 'installedCssChunks[chunkId] = 0;')}, ${runtimeTemplate.basicFunction('e', ['delete installedCssChunks[chunkId];', 'throw e;'])}));`]), '}'])};`]) : '// no chunk loading', '', withHmr ? _webpack.Template.asString(['var oldTags = [];', 'var newTags = [];', `var applyHandler = ${runtimeTemplate.basicFunction('options', [`return { dispose: ${runtimeTemplate.basicFunction('', ['for(var i = 0; i < oldTags.length; i++) {', _webpack.Template.indent(['var oldTag = oldTags[i];', 'if(oldTag.parentNode) oldTag.parentNode.removeChild(oldTag);']), '}', 'oldTags.length = 0;'])}, apply: ${runtimeTemplate.basicFunction('', ['for(var i = 0; i < newTags.length; i++) newTags[i].rel = "stylesheet";', 'newTags.length = 0;'])} };`])}`, `${_webpack.RuntimeGlobals.hmrDownloadUpdateHandlers}.miniCss = ${runtimeTemplate.basicFunction('chunkIds, removedChunks, removedModules, promises, applyHandlers, updatedModulesList', ['applyHandlers.push(applyHandler);', `chunkIds.forEach(${runtimeTemplate.basicFunction('chunkId', [`var href = ${_webpack.RuntimeGlobals.require}.miniCssF(chunkId);`, `var fullhref = ${_webpack.RuntimeGlobals.publicPath} + href;`, 'const oldTag = findStylesheet(href, fullhref);', 'if(!oldTag) return;', `promises.push(new Promise(${runtimeTemplate.basicFunction('resolve, reject', [`var tag = createStylesheet(fullhref, ${runtimeTemplate.basicFunction('', ['tag.as = "style";', 'tag.rel = "preload";', 'resolve();'])}, reject);`, 'oldTags.push(oldTag);', 'newTags.push(tag);'])}));`])});`])}`]) : '// no hmr']); | ||
} | ||
}; |
@@ -10,3 +10,3 @@ "use strict"; | ||
*/ | ||
var normalizeUrl = require('normalize-url'); | ||
var normalizeUrl = require('./normalize-url'); | ||
@@ -71,5 +71,3 @@ var srcByModuleId = Object.create(null); | ||
var reg = new RegExp("".concat(filename, "\\.js$"), 'g'); | ||
return normalizeUrl(src.replace(reg, "".concat(mapRule.replace(/{fileName}/g, filename), ".css")), { | ||
stripWWW: false | ||
}); | ||
return normalizeUrl(src.replace(reg, "".concat(mapRule.replace(/{fileName}/g, filename), ".css"))); | ||
}); | ||
@@ -76,0 +74,0 @@ }; |
@@ -56,2 +56,4 @@ "use strict"; | ||
}); | ||
const insert = typeof options.insert !== 'undefined' ? typeof options.insert === 'function' ? `(${options.insert.toString()})(linkTag)` : Template.asString([`var target = document.querySelector("${options.insert}");`, `target.parentNode.insertBefore(linkTag, target.nextSibling);`]) : Template.asString(['var head = document.getElementsByTagName("head")[0];', 'head.appendChild(linkTag);']); | ||
const attributes = typeof options.attributes === 'object' ? options.attributes : {}; | ||
this.options = Object.assign({ | ||
@@ -61,2 +63,9 @@ filename: DEFAULT_FILENAME, | ||
}, options); | ||
this.runtimeOptions = { | ||
insert | ||
}; | ||
this.runtimeOptions.attributes = Template.asString(Object.entries(attributes).map(entry => { | ||
const [key, value] = entry; | ||
return `linkTag.setAttribute(${JSON.stringify(key)}, ${JSON.stringify(value)});`; | ||
})); | ||
@@ -294,3 +303,3 @@ if (!this.options.chunkFilename) { | ||
}); | ||
return Template.asString([source, '', `// ${pluginName} CSS loading`, `var cssChunks = ${JSON.stringify(chunkMap)};`, 'if(installedCssChunks[chunkId]) promises.push(installedCssChunks[chunkId]);', 'else if(installedCssChunks[chunkId] !== 0 && cssChunks[chunkId]) {', Template.indent(['promises.push(installedCssChunks[chunkId] = new Promise(function(resolve, reject) {', Template.indent([`var href = ${linkHrefPath};`, `var fullhref = ${mainTemplate.requireFn}.p + href;`, 'var existingLinkTags = document.getElementsByTagName("link");', 'for(var i = 0; i < existingLinkTags.length; i++) {', Template.indent(['var tag = existingLinkTags[i];', 'var dataHref = tag.getAttribute("data-href") || tag.getAttribute("href");', 'if(tag.rel === "stylesheet" && (dataHref === href || dataHref === fullhref)) return resolve();']), '}', 'var existingStyleTags = document.getElementsByTagName("style");', 'for(var i = 0; i < existingStyleTags.length; i++) {', Template.indent(['var tag = existingStyleTags[i];', 'var dataHref = tag.getAttribute("data-href");', 'if(dataHref === href || dataHref === fullhref) return resolve();']), '}', 'var linkTag = document.createElement("link");', 'linkTag.rel = "stylesheet";', 'linkTag.type = "text/css";', 'linkTag.onload = resolve;', 'linkTag.onerror = function(event) {', Template.indent(['var request = event && event.target && event.target.src || fullhref;', 'var err = new Error("Loading CSS chunk " + chunkId + " failed.\\n(" + request + ")");', 'err.code = "CSS_CHUNK_LOAD_FAILED";', 'err.request = request;', 'delete installedCssChunks[chunkId]', 'linkTag.parentNode.removeChild(linkTag)', 'reject(err);']), '};', 'linkTag.href = fullhref;', crossOriginLoading ? Template.asString([`if (linkTag.href.indexOf(window.location.origin + '/') !== 0) {`, Template.indent(`linkTag.crossOrigin = ${JSON.stringify(crossOriginLoading)};`), '}']) : '', 'var head = document.getElementsByTagName("head")[0];', 'head.appendChild(linkTag);']), '}).then(function() {', Template.indent(['installedCssChunks[chunkId] = 0;']), '}));']), '}']); | ||
return Template.asString([source, '', `// ${pluginName} CSS loading`, `var cssChunks = ${JSON.stringify(chunkMap)};`, 'if(installedCssChunks[chunkId]) promises.push(installedCssChunks[chunkId]);', 'else if(installedCssChunks[chunkId] !== 0 && cssChunks[chunkId]) {', Template.indent(['promises.push(installedCssChunks[chunkId] = new Promise(function(resolve, reject) {', Template.indent([`var href = ${linkHrefPath};`, `var fullhref = ${mainTemplate.requireFn}.p + href;`, 'var existingLinkTags = document.getElementsByTagName("link");', 'for(var i = 0; i < existingLinkTags.length; i++) {', Template.indent(['var tag = existingLinkTags[i];', 'var dataHref = tag.getAttribute("data-href") || tag.getAttribute("href");', 'if(tag.rel === "stylesheet" && (dataHref === href || dataHref === fullhref)) return resolve();']), '}', 'var existingStyleTags = document.getElementsByTagName("style");', 'for(var i = 0; i < existingStyleTags.length; i++) {', Template.indent(['var tag = existingStyleTags[i];', 'var dataHref = tag.getAttribute("data-href");', 'if(dataHref === href || dataHref === fullhref) return resolve();']), '}', 'var linkTag = document.createElement("link");', this.runtimeOptions.attributes, 'linkTag.rel = "stylesheet";', 'linkTag.type = "text/css";', 'linkTag.onload = resolve;', 'linkTag.onerror = function(event) {', Template.indent(['var request = event && event.target && event.target.src || fullhref;', 'var err = new Error("Loading CSS chunk " + chunkId + " failed.\\n(" + request + ")");', 'err.code = "CSS_CHUNK_LOAD_FAILED";', 'err.request = request;', 'delete installedCssChunks[chunkId]', 'linkTag.parentNode.removeChild(linkTag)', 'reject(err);']), '};', 'linkTag.href = fullhref;', crossOriginLoading ? Template.asString([`if (linkTag.href.indexOf(window.location.origin + '/') !== 0) {`, Template.indent(`linkTag.crossOrigin = ${JSON.stringify(crossOriginLoading)};`), '}']) : '', this.runtimeOptions.insert]), '}).then(function() {', Template.indent(['installedCssChunks[chunkId] = 0;']), '}));']), '}']); | ||
} | ||
@@ -311,3 +320,3 @@ | ||
compilation.addRuntimeModule(chunk, new _webpack.default.runtime.GetChunkFilenameRuntimeModule(_utils.MODULE_TYPE, 'mini-css', `${_webpack.default.RuntimeGlobals.require}.miniCssF`, referencedChunk => referencedChunk.canBeInitial() ? this.options.filename : this.options.chunkFilename, true)); | ||
compilation.addRuntimeModule(chunk, new CssLoadingRuntimeModule(set)); | ||
compilation.addRuntimeModule(chunk, new CssLoadingRuntimeModule(set, this.runtimeOptions)); | ||
}; | ||
@@ -314,0 +323,0 @@ |
@@ -18,5 +18,2 @@ { | ||
}, | ||
"hmr": { | ||
"type": "boolean" | ||
}, | ||
"modules": { | ||
@@ -23,0 +20,0 @@ "type": "object", |
@@ -37,8 +37,2 @@ "use strict"; | ||
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } | ||
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } | ||
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } | ||
const pluginName = 'mini-css-extract-plugin'; | ||
@@ -52,5 +46,5 @@ const isWebpack4 = _webpack.version[0] === '4'; | ||
// ${Date.now()} | ||
var cssReload = require(${_loaderUtils.default.stringifyRequest(context.context, _path.default.join(__dirname, 'hmr/hotModuleReplacement.js'))})(module.id, ${JSON.stringify(_objectSpread(_objectSpread({}, context.options), {}, { | ||
var cssReload = require(${_loaderUtils.default.stringifyRequest(context.context, _path.default.join(__dirname, 'hmr/hotModuleReplacement.js'))})(module.id, ${JSON.stringify({ ...context.options, | ||
locals: !!context.locals | ||
}))}); | ||
})}); | ||
module.hot.dispose(cssReload); | ||
@@ -140,2 +134,7 @@ ${accept} | ||
for (const dependency of dependencies) { | ||
if (!dependency.identifier) { | ||
// eslint-disable-next-line no-continue | ||
continue; | ||
} | ||
const count = identifierCountMap.get(dependency.identifier) || 0; | ||
@@ -180,3 +179,6 @@ | ||
if (key !== 'default') { | ||
if (!locals) locals = {}; | ||
if (!locals) { | ||
locals = {}; | ||
} | ||
locals[key] = originalExports[key]; | ||
@@ -183,0 +185,0 @@ } |
@@ -27,4 +27,19 @@ { | ||
"type": "boolean" | ||
}, | ||
"insert": { | ||
"description": "Inserts `<link>` at the given position (https://github.com/webpack-contrib/mini-css-extract-plugin#insert).", | ||
"anyOf": [ | ||
{ | ||
"type": "string" | ||
}, | ||
{ | ||
"instanceof": "Function" | ||
} | ||
] | ||
}, | ||
"attributes": { | ||
"description": "Adds custom attributes to tag (https://github.com/webpack-contrib/mini-css-extract-plugin#attributes).", | ||
"type": "object" | ||
} | ||
} | ||
} |
{ | ||
"name": "mini-css-extract-plugin", | ||
"version": "1.0.0", | ||
"version": "1.1.0", | ||
"description": "extracts CSS into separate files", | ||
@@ -47,3 +47,2 @@ "license": "MIT", | ||
"loader-utils": "^2.0.0", | ||
"normalize-url": "1.9.1", | ||
"schema-utils": "^3.0.0", | ||
@@ -53,5 +52,5 @@ "webpack-sources": "^1.1.0" | ||
"devDependencies": { | ||
"@babel/cli": "^7.11.6", | ||
"@babel/core": "^7.11.6", | ||
"@babel/preset-env": "^7.11.5", | ||
"@babel/cli": "^7.12.1", | ||
"@babel/core": "^7.12.3", | ||
"@babel/preset-env": "^7.12.1", | ||
"@commitlint/cli": "^11.0.0", | ||
@@ -61,15 +60,16 @@ "@commitlint/config-conventional": "^11.0.0", | ||
"@webpack-contrib/eslint-config-webpack": "^3.0.0", | ||
"babel-eslint": "^10.0.2", | ||
"babel-eslint": "^10.1.0", | ||
"babel-jest": "^26.5.2", | ||
"cross-env": "^7.0.2", | ||
"css-loader": "^4.3.0", | ||
"css-loader": "^5.0.0", | ||
"del": "^6.0.0", | ||
"del-cli": "^3.0.1", | ||
"es-check": "^5.1.1", | ||
"eslint": "^7.10.0", | ||
"eslint-config-prettier": "^6.12.0", | ||
"eslint": "^7.11.0", | ||
"eslint-config-prettier": "^6.13.0", | ||
"eslint-plugin-import": "^2.22.1", | ||
"file-loader": "^6.1.0", | ||
"file-loader": "^6.1.1", | ||
"husky": "^4.3.0", | ||
"jest": "^26.5.2", | ||
"jsdom": "^16.4.0", | ||
"lint-staged": "^10.4.0", | ||
@@ -80,4 +80,4 @@ "memfs": "^3.0.2", | ||
"standard-version": "^9.0.0", | ||
"webpack": "^4.44.2", | ||
"webpack-cli": "^3.3.6", | ||
"webpack": "^5.1.3", | ||
"webpack-cli": "^4.1.0", | ||
"webpack-dev-server": "^3.7.2" | ||
@@ -84,0 +84,0 @@ }, |
211
README.md
@@ -76,10 +76,142 @@ <div align="center"> | ||
### `publicPath` | ||
### Plugin Options | ||
| Name | Type | Default | Description | | ||
| :-----------------------------------: | :------------------: | :------------------------------------------------------------------------------: | :------------------------------------------------------- | | ||
| **[`filename`](#filename)** | `{String\|Function}` | `[name].css` | This option determines the name of each output CSS file | | ||
| **[`chunkFilename`](#chunkFilename)** | `{String\|Function}` | `based on filename` | This option determines the name of non-entry chunk files | | ||
| **[`ignoreOrder`](#ignoreOrder)** | `{Boolean}` | `false` | Remove Order Warnings | | ||
| **[`insert`](#insert)** | `{String\|Function}` | `var head = document.getElementsByTagName("head")[0];head.appendChild(linkTag);` | Inserts `<link>` at the given position | | ||
| **[`attributes`](#attributes)** | `{Object}` | `{}` | Adds custom attributes to tag | | ||
#### `filename` | ||
Type: `String|Function` | ||
Default: `[name].css` | ||
This option determines the name of each output CSS file. | ||
Works like [`output.filename`](https://webpack.js.org/configuration/output/#outputfilename) | ||
#### `chunkFilename` | ||
Type: `String|Function` | ||
Default: `based on filename` | ||
> i Specifying `chunkFilename` as a `function` is only available in webpack@5 | ||
This option determines the name of non-entry chunk files. | ||
Works like [`output.chunkFilename`](https://webpack.js.org/configuration/output/#outputchunkfilename) | ||
#### `ignoreOrder` | ||
Type: `Boolean` | ||
Default: `false` | ||
Remove Order Warnings. | ||
See [examples](#remove-order-warnings) below for details. | ||
#### `insert` | ||
Type: `String|Function` | ||
Default: `var head = document.getElementsByTagName("head")[0]; head.appendChild(linkTag);` | ||
By default, the `extract-css-chunks-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. | ||
##### `String` | ||
Allows to setup custom [query selector](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector). | ||
A new `<link>` element will be inserted after the found item. | ||
**webpack.config.js** | ||
```js | ||
new MiniCssExtractPlugin({ | ||
insert: '#some-element', | ||
}); | ||
``` | ||
A new `<link>` element will be inserted after the element with id `some-element`. | ||
##### `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. | ||
**webpack.config.js** | ||
```js | ||
new MiniCssExtractPlugin({ | ||
insert: function (linkTag) { | ||
var 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`. | ||
#### `attributes` | ||
Type: `Object` | ||
Default: `{}` | ||
If defined, the `mini-css-extract-plugin` will attach given attributes with their values on <link> element. | ||
**webpack.config.js** | ||
```js | ||
const MiniCssExtractPlugin = require('mini-css-extract-plugin'); | ||
module.exports = { | ||
plugins: [ | ||
new MiniCssExtractPlugin({ | ||
attributes: { | ||
id: 'target', | ||
'data-target': 'example', | ||
}, | ||
}), | ||
], | ||
module: { | ||
rules: [ | ||
{ | ||
test: /\.css$/i, | ||
use: [MiniCssExtractPlugin.loader, 'css-loader'], | ||
}, | ||
], | ||
}, | ||
}; | ||
``` | ||
Note: It's only applied to dynamically loaded css chunks, if you want to modify link attributes inside html file, please using [html-webpack-plugin](https://github.com/jantimon/html-webpack-plugin) | ||
### Loader Options | ||
| Name | Type | Default | Description | | ||
| :-----------------------------: | :------------------: | :--------------------------------: | :-------------------------------------------------------------------------------- | | ||
| **[`publicPath`](#publicPath)** | `{String\|Function}` | `webpackOptions.output.publicPath` | Specifies a custom public path for the external resources like images, files, etc | | ||
| **[`esModule`](#esModule)** | `{Boolean}` | `true` | Use ES modules syntax | | ||
| **[`modules`](#modules)** | `{Object}` | `undefined` | Configuration CSS Modules | | ||
#### `publicPath` | ||
Type: `String|Function` | ||
Default: the `publicPath` in `webpackOptions.output` | ||
Specifies a custom public path for the target file(s). | ||
Specifies a custom public path for the external resources like images, files, etc inside `CSS`. | ||
Works like [`output.publicPath`](https://webpack.js.org/configuration/output/#outputpublicpath) | ||
#### `String` | ||
##### `String` | ||
@@ -119,3 +251,3 @@ **webpack.config.js** | ||
#### `Function` | ||
##### `Function` | ||
@@ -157,3 +289,3 @@ **webpack.config.js** | ||
### `esModule` | ||
#### `esModule` | ||
@@ -194,3 +326,3 @@ Type: `Boolean` | ||
### `modules` | ||
#### `modules` | ||
@@ -202,3 +334,3 @@ Type: `Object` | ||
#### `namedExport` | ||
##### `namedExport` | ||
@@ -315,2 +447,39 @@ Type: `Boolean` | ||
### Common use case | ||
`mini-css-extract-plugin` is more often used in `production` mode to get separate css files. | ||
For `development` mode (including `webpack-dev-server`) you can use `style-loader`, because it injects CSS into the DOM using multiple <style></style> and works faster. | ||
> i Do not use together `style-loader` and `mini-css-extract-plugin`. | ||
**webpack.config.js** | ||
```js | ||
const MiniCssExtractPlugin = require('mini-css-extract-plugin'); | ||
const devMode = process.env.NODE_ENV !== 'production'; | ||
const plugins = []; | ||
if (!devMode) { | ||
// enable in production only | ||
plugins.push(new MiniCssExtractPlugin()); | ||
} | ||
module.exports = { | ||
plugins, | ||
module: { | ||
rules: [ | ||
{ | ||
test: /\.(sa|sc|c)ss$/, | ||
use: [ | ||
devMode ? 'style-loader' : MiniCssExtractPlugin.loader, | ||
'css-loader', | ||
'postcss-loader', | ||
'sass-loader', | ||
], | ||
}, | ||
], | ||
}, | ||
}; | ||
``` | ||
### The `publicPath` option as function | ||
@@ -358,3 +527,3 @@ | ||
This plugin should be used only on `production` builds without `style-loader` in the loaders chain, especially if you want to have HMR in `development`. | ||
This plugin should not be used with `style-loader` in the loaders chain. | ||
@@ -379,4 +548,4 @@ Here is an example to have both HMR in `development` and your styles extracted in a file for `production` builds. | ||
// both options are optional | ||
filename: devMode ? '[name].css' : '[name].[hash].css', | ||
chunkFilename: devMode ? '[id].css' : '[id].[hash].css', | ||
filename: devMode ? '[name].css' : '[name].[contenthash].css', | ||
chunkFilename: devMode ? '[id].css' : '[id].[contenthash].css', | ||
}), | ||
@@ -428,4 +597,4 @@ ]; | ||
// both options are optional | ||
filename: devMode ? '[name].css' : '[name].[hash].css', | ||
chunkFilename: devMode ? '[id].css' : '[id].[hash].css', | ||
filename: devMode ? '[name].css' : '[name].[contenthash].css', | ||
chunkFilename: devMode ? '[id].css' : '[id].[contenthash].css', | ||
}), | ||
@@ -459,4 +628,3 @@ ]; | ||
To minify the output, use a plugin like [optimize-css-assets-webpack-plugin](https://github.com/NMFR/optimize-css-assets-webpack-plugin). | ||
Setting `optimization.minimizer` overrides the defaults provided by webpack, so make sure to also specify a JS minimizer: | ||
To minify the output, use a plugin like [css-minimizer-webpack-plugin](https://github.com/webpack-contrib/css-minimizer-webpack-plugin). | ||
@@ -466,10 +634,6 @@ **webpack.config.js** | ||
```js | ||
const TerserJSPlugin = require('terser-webpack-plugin'); | ||
const MiniCssExtractPlugin = require('mini-css-extract-plugin'); | ||
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin'); | ||
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin'); | ||
module.exports = { | ||
optimization: { | ||
minimizer: [new TerserJSPlugin({}), new OptimizeCSSAssetsPlugin({})], | ||
}, | ||
plugins: [ | ||
@@ -489,5 +653,14 @@ new MiniCssExtractPlugin({ | ||
}, | ||
optimization: { | ||
minimizer: [ | ||
// For webpack@5 you can use the `...` syntax to extend existing minimizers (i.e. `terser-webpack-plugin`), uncomment the next line | ||
// `...` | ||
new CssMinimizerPlugin(), | ||
], | ||
}, | ||
}; | ||
``` | ||
This will enable CSS optimization only in production mode. If you want to run it also in development set the `optimization.minimize` option to true. | ||
### Using preloaded or inlined CSS | ||
@@ -494,0 +667,0 @@ |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
88527
4
17
1181
873
29
- Removednormalize-url@1.9.1
- Removedis-plain-obj@1.1.0(transitive)
- Removednormalize-url@1.9.1(transitive)
- Removedobject-assign@4.1.1(transitive)
- Removedprepend-http@1.0.4(transitive)
- Removedquery-string@4.3.4(transitive)
- Removedsort-keys@1.1.2(transitive)
- Removedstrict-uri-encode@1.1.0(transitive)