[EDIT] FILE: mini-css-extract-plugin.tar
README.md 0000755 00000071226 15075141406 0006041 0 ustar 00 <div align="center"> <img width="200" height="200" src="https://cdn.worldvectorlogo.com/logos/logo-javascript.svg"> <a href="https://webpack.js.org/"> <img width="200" height="200" vspace="" hspace="25" src="https://cdn.rawgit.com/webpack/media/e7485eb2/logo/icon-square-big.svg"> </a> <h1>mini-css-extract-plugin</h1> </div> [![npm][npm]][npm-url] [![node][node]][node-url] [![tests][tests]][tests-url] [![coverage][cover]][cover-url] [![chat][chat]][chat-url] [![size][size]][size-url] # mini-css-extract-plugin This plugin extracts CSS into separate files. It creates a CSS file per JS file which contains CSS. It supports On-Demand-Loading of CSS and SourceMaps. It builds on top of a new webpack v5 feature and requires webpack 5 to work. Compared to the extract-text-webpack-plugin: - Async loading - No duplicate compilation (performance) - Easier to use - Specific to CSS ## Getting Started To begin, you'll need to install `mini-css-extract-plugin`: ```console npm install --save-dev mini-css-extract-plugin ``` or ```console yarn add -D mini-css-extract-plugin ``` or ```console pnpm add -D mini-css-extract-plugin ``` It's recommended to combine `mini-css-extract-plugin` with the [`css-loader`](https://github.com/webpack-contrib/css-loader) Then add the loader and the plugin to your `webpack` config. For example: **style.css** ```css body { background: green; } ``` **component.js** ```js import "./style.css"; ``` **webpack.config.js** ```js const MiniCssExtractPlugin = require("mini-css-extract-plugin"); module.exports = { plugins: [new MiniCssExtractPlugin()], module: { rules: [ { test: /\.css$/i, use: [MiniCssExtractPlugin.loader, "css-loader"], }, ], }, }; ``` > **Warning** > > Note that if you import CSS from your webpack entrypoint or import styles in the [initial](https://webpack.js.org/concepts/under-the-hood/#chunks) chunk, `mini-css-extract-plugin` will not load this CSS into the page. Please use [`html-webpack-plugin`](https://github.com/jantimon/html-webpack-plugin) for automatic generation `link` tags or create `index.html` file with `link` tag. > **Warning** > > Source maps works only for `source-map`/`nosources-source-map`/`hidden-nosources-source-map`/`hidden-source-map` values because CSS only supports source maps with the `sourceMappingURL` comment (i.e. `//# sourceMappingURL=style.css.map`). If you need set `devtool` to another value you can enable source maps generation for extracted CSS using [`sourceMap: true`](https://github.com/webpack-contrib/css-loader#sourcemap) for `css-loader`. ## Options ### Plugin Options - **[`filename`](#filename)** - **[`chunkFilename`](#chunkFilename)** - **[`ignoreOrder`](#ignoreOrder)** - **[`insert`](#insert)** - **[`attributes`](#attributes)** - **[`linkType`](#linkType)** - **[`runtime`](#runtime)** - **[`experimentalUseImportModule`](#experimentalUseImportModule)** #### `filename` Type: ```ts type filename = | string | ((pathData: PathData, assetInfo?: AssetInfo) => string); ``` 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: ```ts type chunkFilename = | string | ((pathData: PathData, assetInfo?: AssetInfo) => string); ``` Default: `based on filename` > 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: ```ts type ignoreOrder = boolean; ``` Default: `false` Remove Order Warnings. See [examples](#remove-order-warnings) below for details. #### `insert` Type: ```ts type insert = string | ((linkTag: HTMLLinkElement) => void); ``` Default: `document.head.appendChild(linkTag);` Inserts the `link` tag at the given position for [non-initial (async)](https://webpack.js.org/concepts/under-the-hood/#chunks) CSS chunks > **Warning** > > Only for [non-initial (async)](https://webpack.js.org/concepts/under-the-hood/#chunks) chunks. 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 insertion. 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: ```ts type attributes = Record<string, string>}; ``` Default: `{}` > **Warning** > > Only for [non-initial (async)](https://webpack.js.org/concepts/under-the-hood/#chunks) chunks. 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) #### `linkType` Type: ```ts type linkType = string | boolean; ``` Default: `text/css` This option allows loading asynchronous chunks with a custom link type, such as `<link type="text/css" ...>`. ##### `string` Possible values: `text/css` **webpack.config.js** ```js const MiniCssExtractPlugin = require("mini-css-extract-plugin"); module.exports = { plugins: [ new MiniCssExtractPlugin({ linkType: "text/css", }), ], module: { rules: [ { test: /\.css$/i, use: [MiniCssExtractPlugin.loader, "css-loader"], }, ], }, }; ``` ##### `boolean` `false` disables the link `type` attribute **webpack.config.js** ```js const MiniCssExtractPlugin = require("mini-css-extract-plugin"); module.exports = { plugins: [ new MiniCssExtractPlugin({ linkType: false, }), ], module: { rules: [ { test: /\.css$/i, use: [MiniCssExtractPlugin.loader, "css-loader"], }, ], }, }; ``` #### `runtime` Type: ```ts type runtime = boolean; ``` Default: `true` Allows to enable/disable the runtime generation. CSS will be still extracted and can be used for a custom loading methods. For example, you can use [assets-webpack-plugin](https://github.com/ztoben/assets-webpack-plugin) to retrieve them then use your own runtime code to download assets when needed. `false` to skip. **webpack.config.js** ```js const MiniCssExtractPlugin = require("mini-css-extract-plugin"); module.exports = { plugins: [ new MiniCssExtractPlugin({ runtime: false, }), ], module: { rules: [ { test: /\.css$/i, use: [MiniCssExtractPlugin.loader, "css-loader"], }, ], }, }; ``` #### `experimentalUseImportModule` Type: ```ts type experimentalUseImportModule = boolean; ``` Default: `undefined` Enabled by default if not explicitly enabled (i.e. `true` and `false` allow you to explicitly control this option) and new API is available (at least webpack `5.52.0` is required). Boolean values are available since version `5.33.2`, but you need to enable `experiments.executeModule` (not required from webpack `5.52.0`). Use a new webpack API to execute modules instead of child compilers. This improves performance and memory usage a lot. When combined with `experiments.layers`, this adds a `layer` option to the loader options to specify the layer of the css execution. **webpack.config.js** ```js const MiniCssExtractPlugin = require("mini-css-extract-plugin"); module.exports = { plugins: [ new MiniCssExtractPlugin({ // You don't need this for `>= 5.52.0` due to the fact that this is enabled by default // Required only for `>= 5.33.2 & <= 5.52.0` // Not available/unsafe for `<= 5.33.2` experimentalUseImportModule: true, }), ], module: { rules: [ { test: /\.css$/i, use: [MiniCssExtractPlugin.loader, "css-loader"], }, ], }, }; ``` ### Loader Options - **[`publicPath`](#publicPath)** - **[`emit`](#emit)** - **[`esModule`](#esModule)** #### `publicPath` Type: ```ts type publicPath = | string | ((resourcePath: string, rootContext: string) => string); ``` Default: the `publicPath` in `webpackOptions.output` 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` **webpack.config.js** ```js const MiniCssExtractPlugin = require("mini-css-extract-plugin"); module.exports = { plugins: [ new MiniCssExtractPlugin({ // Options similar to the same options in webpackOptions.output // both options are optional filename: "[name].css", chunkFilename: "[id].css", }), ], module: { rules: [ { test: /\.css$/, use: [ { loader: MiniCssExtractPlugin.loader, options: { publicPath: "/public/path/to/", }, }, "css-loader", ], }, ], }, }; ``` ##### `function` **webpack.config.js** ```js const MiniCssExtractPlugin = require("mini-css-extract-plugin"); module.exports = { plugins: [ new MiniCssExtractPlugin({ // Options similar to the same options in webpackOptions.output // both options are optional filename: "[name].css", chunkFilename: "[id].css", }), ], module: { rules: [ { test: /\.css$/, use: [ { loader: MiniCssExtractPlugin.loader, options: { publicPath: (resourcePath, context) => { return path.relative(path.dirname(resourcePath), context) + "/"; }, }, }, "css-loader", ], }, ], }, }; ``` #### `emit` Type: ```ts type emit = boolean; ``` Default: `true` If true, emits a file (writes a file to the filesystem). If false, the plugin will extract the CSS but **will not** emit the file. It is often useful to disable this option for server-side packages. #### `esModule` Type: ```ts type esModule = boolean; ``` Default: `true` By default, `mini-css-extract-plugin` generates JS modules that use the ES modules syntax. There are some cases in which using ES modules is beneficial, like in the case of [module concatenation](https://webpack.js.org/plugins/module-concatenation-plugin/) and [tree shaking](https://webpack.js.org/guides/tree-shaking/). You can enable a CommonJS syntax using: **webpack.config.js** ```js const MiniCssExtractPlugin = require("mini-css-extract-plugin"); module.exports = { plugins: [new MiniCssExtractPlugin()], module: { rules: [ { test: /\.css$/i, use: [ { loader: MiniCssExtractPlugin.loader, options: { esModule: false, }, }, "css-loader", ], }, ], }, }; ``` ## Examples ### Recommended For `production` builds it's recommended to extract the CSS from your bundle being able to use parallel loading of CSS/JS resources later on. This can be achieved by using the `mini-css-extract-plugin`, because it creates separate css files. For `development` mode (including `webpack-dev-server`) you can use [style-loader](https://github.com/webpack-contrib/style-loader), because it injects CSS into the DOM using multiple <style></style> and works faster. > Do not use `style-loader` and `mini-css-extract-plugin` together. **webpack.config.js** ```js const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const devMode = process.env.NODE_ENV !== "production"; module.exports = { module: { rules: [ { test: /\.(sa|sc|c)ss$/, use: [ devMode ? "style-loader" : MiniCssExtractPlugin.loader, "css-loader", "postcss-loader", "sass-loader", ], }, ], }, plugins: [].concat(devMode ? [] : [new MiniCssExtractPlugin()]), }; ``` ### Minimal example **webpack.config.js** ```js const MiniCssExtractPlugin = require("mini-css-extract-plugin"); module.exports = { plugins: [ new MiniCssExtractPlugin({ // Options similar to the same options in webpackOptions.output // all options are optional filename: "[name].css", chunkFilename: "[id].css", ignoreOrder: false, // Enable to remove warnings about conflicting order }), ], module: { rules: [ { test: /\.css$/, use: [ { loader: MiniCssExtractPlugin.loader, options: { // you can specify a publicPath here // by default it uses publicPath in webpackOptions.output publicPath: "../", }, }, "css-loader", ], }, ], }, }; ``` ### Named export for CSS Modules > ⚠ Names of locals are converted to `camelCase`. > ⚠ It is not allowed to use JavaScript reserved words in css class names. > ⚠ Options `esModule` and `modules.namedExport` in `css-loader` should be enabled. **styles.css** ```css .foo-baz { color: red; } .bar { color: blue; } ``` **index.js** ```js import { fooBaz, bar } from "./styles.css"; console.log(fooBaz, bar); ``` You can enable a ES module named export using: **webpack.config.js** ```js const MiniCssExtractPlugin = require("mini-css-extract-plugin"); module.exports = { plugins: [new MiniCssExtractPlugin()], module: { rules: [ { test: /\.css$/, use: [ { loader: MiniCssExtractPlugin.loader, }, { loader: "css-loader", options: { esModule: true, modules: { namedExport: true, localIdentName: "foo__[name]__[local]", }, }, }, ], }, ], }, }; ``` ### The `publicPath` option as function **webpack.config.js** ```js const MiniCssExtractPlugin = require("mini-css-extract-plugin"); module.exports = { plugins: [ new MiniCssExtractPlugin({ // Options similar to the same options in webpackOptions.output // both options are optional filename: "[name].css", chunkFilename: "[id].css", }), ], module: { rules: [ { test: /\.css$/, use: [ { loader: MiniCssExtractPlugin.loader, options: { publicPath: (resourcePath, context) => { // publicPath is the relative path of the resource to the context // e.g. for ./css/admin/main.css the publicPath will be ../../ // while for ./css/main.css the publicPath will be ../ return path.relative(path.dirname(resourcePath), context) + "/"; }, }, }, "css-loader", ], }, ], }, }; ``` ### Advanced configuration example This plugin should not be used with `style-loader` in the loaders chain. Here is an example to have both HMR in `development` and your styles extracted in a file for `production` builds. (Loaders options left out for clarity, adapt accordingly to your needs.) You should not use `HotModuleReplacementPlugin` plugin if you are using a `webpack-dev-server`. `webpack-dev-server` enables / disables HMR using `hot` option. **webpack.config.js** ```js const webpack = require("webpack"); const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const devMode = process.env.NODE_ENV !== "production"; const plugins = [ new MiniCssExtractPlugin({ // Options similar to the same options in webpackOptions.output // both options are optional filename: devMode ? "[name].css" : "[name].[contenthash].css", chunkFilename: devMode ? "[id].css" : "[id].[contenthash].css", }), ]; if (devMode) { // only enable hot in development plugins.push(new webpack.HotModuleReplacementPlugin()); } module.exports = { plugins, module: { rules: [ { test: /\.(sa|sc|c)ss$/, use: [ MiniCssExtractPlugin.loader, "css-loader", "postcss-loader", "sass-loader", ], }, ], }, }; ``` ### Hot Module Reloading (HMR) > **Note** > > HMR is automatically supported in webpack 5. No need to configure it. Skip the following: The `mini-css-extract-plugin` supports hot reloading of actual css files in development. Some options are provided to enable HMR of both standard stylesheets and locally scoped CSS or CSS modules. Below is an example configuration of mini-css for HMR use with CSS modules. You should not use `HotModuleReplacementPlugin` plugin if you are using a `webpack-dev-server`. `webpack-dev-server` enables / disables HMR using `hot` option. **webpack.config.js** ```js const webpack = require("webpack"); const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const plugins = [ new MiniCssExtractPlugin({ // Options similar to the same options in webpackOptions.output // both options are optional filename: devMode ? "[name].css" : "[name].[contenthash].css", chunkFilename: devMode ? "[id].css" : "[id].[contenthash].css", }), ]; if (devMode) { // only enable hot in development plugins.push(new webpack.HotModuleReplacementPlugin()); } module.exports = { plugins, module: { rules: [ { test: /\.css$/, use: [ { loader: MiniCssExtractPlugin.loader, options: {}, }, "css-loader", ], }, ], }, }; ``` ### Minimizing For Production To minify the output, use a plugin like [css-minimizer-webpack-plugin](https://github.com/webpack-contrib/css-minimizer-webpack-plugin). **webpack.config.js** ```js const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const CssMinimizerPlugin = require("css-minimizer-webpack-plugin"); module.exports = { plugins: [ new MiniCssExtractPlugin({ filename: "[name].css", chunkFilename: "[id].css", }), ], module: { rules: [ { test: /\.css$/, use: [MiniCssExtractPlugin.loader, "css-loader"], }, ], }, 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 The runtime code detects already added CSS via `<link>` or `<style>` tag. This can be useful when injecting CSS on server-side for Server-Side-Rendering. The `href` of the `<link>` tag has to match the URL that will be used for loading the CSS chunk. The `data-href` attribute can be used for `<link>` and `<style>` too. When inlining CSS `data-href` must be used. ### Extracting all CSS in a single file The CSS can be extracted in one CSS file using `optimization.splitChunks.cacheGroups`. **webpack.config.js** ```js const MiniCssExtractPlugin = require("mini-css-extract-plugin"); module.exports = { optimization: { splitChunks: { cacheGroups: { styles: { name: "styles", type: "css/mini-extract", chunks: "all", enforce: true, }, }, }, }, plugins: [ new MiniCssExtractPlugin({ filename: "[name].css", }), ], module: { rules: [ { test: /\.css$/, use: [MiniCssExtractPlugin.loader, "css-loader"], }, ], }, }; ``` Note that `type` should be used instead of `test` in Webpack 5, or else an extra `.js` file can be generated besides the `.css` file. This is because `test` doesn't know which modules should be dropped (in this case, it won't detect that `.js` should be dropped). ### Extracting CSS based on entry You may also extract the CSS based on the webpack entry name. This is especially useful if you import routes dynamically but want to keep your CSS bundled according to entry. This also prevents the CSS duplication issue one had with the ExtractTextPlugin. ```js const path = require("path"); const MiniCssExtractPlugin = require("mini-css-extract-plugin"); module.exports = { entry: { foo: path.resolve(__dirname, "src/foo"), bar: path.resolve(__dirname, "src/bar"), }, optimization: { splitChunks: { cacheGroups: { fooStyles: { type: "css/mini-extract", name: "styles_foo", chunks: (chunk) => { return chunk.name === "foo"; }, enforce: true, }, barStyles: { type: "css/mini-extract", name: "styles_bar", chunks: (chunk) => { return chunk.name === "bar"; }, enforce: true, }, }, }, }, plugins: [ new MiniCssExtractPlugin({ filename: "[name].css", }), ], module: { rules: [ { test: /\.css$/, use: [MiniCssExtractPlugin.loader, "css-loader"], }, ], }, }; ``` ### Filename Option as function With the `filename` 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 `filename` to output the generated css into a different directory. **webpack.config.js** ```js const MiniCssExtractPlugin = require("mini-css-extract-plugin"); module.exports = { plugins: [ new MiniCssExtractPlugin({ filename: ({ chunk }) => `${chunk.name.replace("/js/", "/css/")}.css`, }), ], module: { rules: [ { test: /\.css$/, use: [MiniCssExtractPlugin.loader, "css-loader"], }, ], }, }; ``` ### Long Term Caching For long term caching use `filename: "[contenthash].css"`. Optionally add `[name]`. **webpack.config.js** ```js const MiniCssExtractPlugin = require("mini-css-extract-plugin"); module.exports = { plugins: [ new MiniCssExtractPlugin({ filename: "[name].[contenthash].css", chunkFilename: "[id].[contenthash].css", }), ], module: { rules: [ { test: /\.css$/, use: [MiniCssExtractPlugin.loader, "css-loader"], }, ], }, }; ``` ### Remove Order Warnings For projects where css ordering has been mitigated through consistent use of scoping or naming conventions, such as [CSS Modules](https://github.com/css-modules/css-modules), the css order warnings can be disabled by setting the ignoreOrder flag to true for the plugin. **webpack.config.js** ```js const MiniCssExtractPlugin = require("mini-css-extract-plugin"); module.exports = { plugins: [ new MiniCssExtractPlugin({ ignoreOrder: true, }), ], module: { rules: [ { test: /\.css$/i, use: [MiniCssExtractPlugin.loader, "css-loader"], }, ], }, }; ``` ### Multiple Themes **webpack.config.js** ```js const MiniCssExtractPlugin = require("mini-css-extract-plugin"); module.exports = { entry: "./src/index.js", module: { rules: [ { test: /\.s[ac]ss$/i, oneOf: [ { resourceQuery: "?dark", use: [ MiniCssExtractPlugin.loader, "css-loader", { loader: "sass-loader", options: { additionalData: `@use 'dark-theme/vars' as vars;`, }, }, ], }, { use: [ MiniCssExtractPlugin.loader, "css-loader", { loader: "sass-loader", options: { additionalData: `@use 'light-theme/vars' as vars;`, }, }, ], }, ], }, ], }, plugins: [ new MiniCssExtractPlugin({ filename: "[name].css", attributes: { id: "theme", }, }), ], }; ``` **src/index.js** ```js import "./style.scss"; let theme = "light"; const themes = {}; themes[theme] = document.querySelector("#theme"); async function loadTheme(newTheme) { // eslint-disable-next-line no-console console.log(`CHANGE THEME - ${newTheme}`); const themeElement = document.querySelector("#theme"); if (themeElement) { themeElement.remove(); } if (themes[newTheme]) { // eslint-disable-next-line no-console console.log(`THEME ALREADY LOADED - ${newTheme}`); document.head.appendChild(themes[newTheme]); return; } if (newTheme === "dark") { // eslint-disable-next-line no-console console.log(`LOADING THEME - ${newTheme}`); import(/* webpackChunkName: "dark" */ "./style.scss?dark").then(() => { themes[newTheme] = document.querySelector("#theme"); // eslint-disable-next-line no-console console.log(`LOADED - ${newTheme}`); }); } } document.onclick = () => { if (theme === "light") { theme = "dark"; } else { theme = "light"; } loadTheme(theme); }; ``` **src/dark-theme/\_vars.scss** ```scss $background: black; ``` **src/light-theme/\_vars.scss** ```scss $background: white; ``` **src/styles.scss** ```scss body { background-color: vars.$background; } ``` **public/index.html** ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Document</title> <link id="theme" rel="stylesheet" type="text/css" href="./main.css" /> </head> <body> <script src="./main.js"></script> </body> </html> ``` ### 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: - [Media Query Plugin](https://github.com/SassNinja/media-query-plugin) - [Media Query Splitting Plugin](https://github.com/mike-diamond/media-query-splitting-plugin) ## Contributing Please take a moment to read our contributing guidelines if you haven't yet done so. [CONTRIBUTING](./.github/CONTRIBUTING.md) ## License [MIT](./LICENSE) [npm]: https://img.shields.io/npm/v/mini-css-extract-plugin.svg [npm-url]: https://npmjs.com/package/mini-css-extract-plugin [node]: https://img.shields.io/node/v/mini-css-extract-plugin.svg [node-url]: https://nodejs.org [tests]: https://github.com/webpack-contrib/mini-css-extract-plugin/workflows/mini-css-extract-plugin/badge.svg [tests-url]: https://github.com/webpack-contrib/mini-css-extract-plugin/actions [cover]: https://codecov.io/gh/webpack-contrib/mini-css-extract-plugin/branch/master/graph/badge.svg [cover-url]: https://codecov.io/gh/webpack-contrib/mini-css-extract-plugin [chat]: https://badges.gitter.im/webpack/webpack.svg [chat-url]: https://gitter.im/webpack/webpack [size]: https://packagephobia.now.sh/badge?p=mini-css-extract-plugin [size-url]: https://packagephobia.now.sh/result?p=mini-css-extract-plugin types/hmr/hotModuleReplacement.d.ts 0000755 00000000153 15075141406 0013415 0 ustar 00 declare function _exports(moduleId: TODO, options: TODO): TODO; export = _exports; export type TODO = any; types/hmr/normalize-url.d.ts 0000755 00000000111 15075141406 0012067 0 ustar 00 declare function _exports(urlString: string): string; export = _exports; types/index.d.ts 0000755 00000016760 15075141406 0007631 0 ustar 00 export = MiniCssExtractPlugin; declare class MiniCssExtractPlugin { /** * @param {Compiler["webpack"]} webpack * @returns {CssModuleConstructor} */ static getCssModule(webpack: Compiler["webpack"]): CssModuleConstructor; /** * @param {Compiler["webpack"]} webpack * @returns {CssDependencyConstructor} */ static getCssDependency( webpack: Compiler["webpack"] ): CssDependencyConstructor; /** * @param {PluginOptions} [options] */ constructor(options?: PluginOptions | undefined); /** * @private * @type {WeakMap<Chunk, Set<CssModule>>} * @private */ private _sortedModulesCache; /** * @private * @type {NormalizedPluginOptions} */ private options; /** * @private * @type {RuntimeOptions} */ private runtimeOptions; /** * @param {Compiler} compiler */ apply(compiler: Compiler): void; /** * @private * @param {Chunk} chunk * @param {ChunkGraph} chunkGraph * @returns {Iterable<Module>} */ private getChunkModules; /** * @private * @param {Compilation} compilation * @param {Chunk} chunk * @param {CssModule[]} modules * @param {Compilation["requestShortener"]} requestShortener * @returns {Set<CssModule>} */ private sortModules; /** * @private * @param {Compiler} compiler * @param {Compilation} compilation * @param {Chunk} chunk * @param {CssModule[]} modules * @param {Compiler["requestShortener"]} requestShortener * @param {string} filenameTemplate * @param {Parameters<Exclude<Required<Configuration>['output']['filename'], string | undefined>>[0]} pathData * @returns {Source} */ private renderContentAsset; } declare namespace MiniCssExtractPlugin { export { pluginName, pluginSymbol, loader, Schema, Compiler, Compilation, ChunkGraph, Chunk, ChunkGroup, Module, Dependency, Source, Configuration, WebpackError, AssetInfo, LoaderDependency, LoaderOptions, PluginOptions, NormalizedPluginOptions, RuntimeOptions, TODO, CssModule, CssModuleDependency, CssModuleConstructor, CssDependency, CssDependencyOptions, CssDependencyConstructor, }; } type Compiler = import("webpack").Compiler; type CssModuleConstructor = new (dependency: CssModuleDependency) => CssModule; type CssDependencyConstructor = new ( loaderDependency: CssDependencyOptions, context: string | null, identifierIndex: number ) => CssDependency; type PluginOptions = { filename?: Required<Configuration>["output"]["filename"]; chunkFilename?: Required<Configuration>["output"]["chunkFilename"]; ignoreOrder?: boolean | undefined; insert?: string | ((linkTag: HTMLLinkElement) => void) | undefined; attributes?: Record<string, string> | undefined; linkType?: string | false | undefined; runtime?: boolean | undefined; experimentalUseImportModule?: boolean | undefined; }; /** @typedef {import("schema-utils/declarations/validate").Schema} Schema */ /** @typedef {import("webpack").Compiler} Compiler */ /** @typedef {import("webpack").Compilation} Compilation */ /** @typedef {import("webpack").ChunkGraph} ChunkGraph */ /** @typedef {import("webpack").Chunk} Chunk */ /** @typedef {Parameters<import("webpack").Chunk["isInGroup"]>[0]} ChunkGroup */ /** @typedef {import("webpack").Module} Module */ /** @typedef {import("webpack").Dependency} Dependency */ /** @typedef {import("webpack").sources.Source} Source */ /** @typedef {import("webpack").Configuration} Configuration */ /** @typedef {import("webpack").WebpackError} WebpackError */ /** @typedef {import("webpack").AssetInfo} AssetInfo */ /** @typedef {import("./loader.js").Dependency} LoaderDependency */ /** * @typedef {Object} LoaderOptions * @property {string | ((resourcePath: string, rootContext: string) => string)} [publicPath] * @property {boolean} [emit] * @property {boolean} [esModule] * @property {string} [layer] */ /** * @typedef {Object} PluginOptions * @property {Required<Configuration>['output']['filename']} [filename] * @property {Required<Configuration>['output']['chunkFilename']} [chunkFilename] * @property {boolean} [ignoreOrder] * @property {string | ((linkTag: HTMLLinkElement) => void)} [insert] * @property {Record<string, string>} [attributes] * @property {string | false | 'text/css'} [linkType] * @property {boolean} [runtime] * @property {boolean} [experimentalUseImportModule] */ /** * @typedef {Object} NormalizedPluginOptions * @property {Required<Configuration>['output']['filename']} filename * @property {Required<Configuration>['output']['chunkFilename']} [chunkFilename] * @property {boolean} ignoreOrder * @property {string | ((linkTag: HTMLLinkElement) => void)} [insert] * @property {Record<string, string>} [attributes] * @property {string | false | 'text/css'} [linkType] * @property {boolean} runtime * @property {boolean} [experimentalUseImportModule] */ /** * @typedef {Object} RuntimeOptions * @property {string | ((linkTag: HTMLLinkElement) => void) | undefined} insert * @property {string | false | 'text/css'} linkType * @property {Record<string, string> | undefined} attributes */ /** @typedef {any} TODO */ declare const pluginName: "mini-css-extract-plugin"; declare const pluginSymbol: unique symbol; declare var loader: string; type Schema = import("schema-utils/declarations/validate").Schema; type Compilation = import("webpack").Compilation; type ChunkGraph = import("webpack").ChunkGraph; type Chunk = import("webpack").Chunk; type ChunkGroup = Parameters<import("webpack").Chunk["isInGroup"]>[0]; type Module = import("webpack").Module; type Dependency = import("webpack").Dependency; type Source = import("webpack").sources.Source; type Configuration = import("webpack").Configuration; type WebpackError = import("webpack").WebpackError; type AssetInfo = import("webpack").AssetInfo; type LoaderDependency = import("./loader.js").Dependency; type LoaderOptions = { publicPath?: | string | ((resourcePath: string, rootContext: string) => string) | undefined; emit?: boolean | undefined; esModule?: boolean | undefined; layer?: string | undefined; }; type NormalizedPluginOptions = { filename: Required<Configuration>["output"]["filename"]; chunkFilename?: Required<Configuration>["output"]["chunkFilename"]; ignoreOrder: boolean; insert?: string | ((linkTag: HTMLLinkElement) => void) | undefined; attributes?: Record<string, string> | undefined; linkType?: string | false | undefined; runtime: boolean; experimentalUseImportModule?: boolean | undefined; }; type RuntimeOptions = { insert: string | ((linkTag: HTMLLinkElement) => void) | undefined; linkType: string | false | "text/css"; attributes: Record<string, string> | undefined; }; type TODO = any; type CssModule = import("webpack").Module & { content: Buffer; media?: string | undefined; sourceMap?: Buffer | undefined; supports?: string | undefined; layer?: string | undefined; assets?: | { [key: string]: any; } | undefined; assetsInfo?: Map<string, import("webpack").AssetInfo> | undefined; }; type CssModuleDependency = { context: string | null; identifier: string; identifierIndex: number; content: Buffer; sourceMap?: Buffer | undefined; media?: string | undefined; supports?: string | undefined; layer?: TODO; assetsInfo?: Map<string, import("webpack").AssetInfo> | undefined; assets?: | { [key: string]: any; } | undefined; }; type CssDependency = Dependency & CssModuleDependency; type CssDependencyOptions = Omit<LoaderDependency, "context">; types/utils.d.ts 0000755 00000003561 15075141406 0007655 0 ustar 00 export type Compilation = import("webpack").Compilation; export type Module = import("webpack").Module; export type LoaderContext = import("webpack").LoaderContext<any>; /** @typedef {import("webpack").Compilation} Compilation */ /** @typedef {import("webpack").Module} Module */ /** @typedef {import("webpack").LoaderContext<any>} LoaderContext */ /** * @returns {boolean} */ export function trueFn(): boolean; /** * @param {Compilation} compilation * @param {string | number} id * @returns {null | Module} */ export function findModuleById( compilation: Compilation, id: string | number ): null | Module; /** * @param {LoaderContext} loaderContext * @param {string | Buffer} code * @param {string} filename * @returns {object} */ export function evalModuleCode( loaderContext: LoaderContext, code: string | Buffer, filename: string ): object; /** * @param {Module} a * @param {Module} b * @returns {0 | 1 | -1} */ export function compareModulesByIdentifier(a: Module, b: Module): 0 | 1 | -1; export const MODULE_TYPE: "css/mini-extract"; export const AUTO_PUBLIC_PATH: "__mini_css_extract_plugin_public_path_auto__"; export const ABSOLUTE_PUBLIC_PATH: "webpack:///mini-css-extract-plugin/"; export const BASE_URI: "webpack://"; export const SINGLE_DOT_PATH_SEGMENT: "__mini_css_extract_plugin_single_dot_path_segment__"; /** * @param {LoaderContext} loaderContext * @param {string} request * @returns {string} */ export function stringifyRequest( loaderContext: LoaderContext, request: string ): string; /** * * @param {string | function} value * @returns {string} */ export function stringifyLocal(value: string | Function): string; /** * @param {string} filename * @param {string} outputPath * @param {boolean} enforceRelative * @returns {string} */ export function getUndoPath( filename: string, outputPath: string, enforceRelative: boolean ): string; types/loader.d.ts 0000755 00000002163 15075141406 0007760 0 ustar 00 export type Schema = import("schema-utils/declarations/validate").Schema; export type Compiler = import("webpack").Compiler; export type Compilation = import("webpack").Compilation; export type Chunk = import("webpack").Chunk; export type Module = import("webpack").Module; export type Source = import("webpack").sources.Source; export type AssetInfo = import("webpack").AssetInfo; export type NormalModule = import("webpack").NormalModule; export type LoaderOptions = import("./index.js").LoaderOptions; export type Locals = { [key: string]: string | Function; }; export type TODO = any; export type Dependency = { identifier: string; context: string | null; content: Buffer; media: string; supports?: string | undefined; layer?: string | undefined; sourceMap?: Buffer | undefined; }; /** * @this {import("webpack").LoaderContext<LoaderOptions>} * @param {string} request */ export function pitch( this: import("webpack").LoaderContext<MiniCssExtractPlugin.LoaderOptions>, request: string ): void; import MiniCssExtractPlugin = require("./index"); declare function _default(): void; export { _default as default }; LICENSE 0000755 00000002057 15075141406 0005563 0 ustar 00 Copyright JS Foundation and other contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. package.json 0000755 00000006243 15075141406 0007045 0 ustar 00 { "name": "mini-css-extract-plugin", "version": "2.7.2", "description": "extracts CSS into separate files", "license": "MIT", "repository": "webpack-contrib/mini-css-extract-plugin", "author": "Tobias Koppers @sokra", "homepage": "https://github.com/webpack-contrib/mini-css-extract-plugin", "bugs": "https://github.com/webpack-contrib/mini-css-extract-plugin/issues", "funding": { "type": "opencollective", "url": "https://opencollective.com/webpack" }, "main": "dist/index.js", "types": "types/index.d.ts", "engines": { "node": ">= 12.13.0" }, "scripts": { "start": "npm run build -- -w", "prebuild": "npm run clean", "build:types": "tsc --declaration --emitDeclarationOnly --outDir types && prettier \"types/**/*.ts\" --write", "build:code": "cross-env NODE_ENV=production babel src -d dist --copy-files", "build": "npm-run-all -p \"build:**\"", "postbuild": "es-check es5 dist/hmr/hotModuleReplacement.js", "clean": "del-cli dist", "commitlint": "commitlint --from=master", "lint:prettier": "prettier \"{**/*,*}.{js,json,md,yml,css,ts}\" --list-different", "lint:js": "eslint --cache .", "lint:spelling": "cspell \"**/*.*\"", "lint:types": "tsc --pretty --noEmit", "lint": "npm-run-all -l -p \"lint:**\"", "prepare": "husky install && npm run build", "release": "standard-version", "security": "npm audit --production", "test:only": "cross-env NODE_ENV=test jest", "test:only:experimental": "EXPERIMENTAL_USE_IMPORT_MODULE=true cross-env NODE_ENV=test jest", "test:watch": "npm run test:only -- --watch", "test:coverage": "npm run test:only -- --collectCoverageFrom=\"src/**/*.js\" --coverage", "test:manual": "npm run build && webpack serve ./test/manual/src/index.js --open --config ./test/manual/webpack.config.js", "pretest": "npm run lint", "test": "cross-env NODE_ENV=test npm run test:coverage" }, "files": [ "dist", "types" ], "peerDependencies": { "webpack": "^5.0.0" }, "dependencies": { "schema-utils": "^4.0.0" }, "devDependencies": { "@babel/cli": "^7.19.3", "@babel/core": "^7.19.6", "@babel/eslint-parser": "^7.19.1", "@babel/preset-env": "^7.19.4", "@commitlint/cli": "^17.2.0", "@commitlint/config-conventional": "^17.2.0", "@webpack-contrib/eslint-config-webpack": "^3.0.0", "babel-jest": "^28.1.3", "bootstrap": "^4.6.2", "cross-env": "^7.0.3", "cspell": "^6.16.0", "css-loader": "^6.7.0", "del": "^6.0.0", "del-cli": "^4.0.0", "es-check": "^7.0.1", "eslint": "^8.29.0", "eslint-config-prettier": "^8.5.0", "eslint-plugin-import": "^2.25.4", "file-loader": "^6.2.0", "husky": "^7.0.0", "jest": "^28.1.3", "jest-environment-jsdom": "^28.1.3", "jsdom": "^19.0.0", "lint-staged": "^12.3.4", "memfs": "^3.4.9", "npm-run-all": "^4.1.5", "prettier": "^2.7.1", "sass": "^1.55.0", "sass-loader": "^12.6.0", "standard-version": "^9.3.0", "typescript": "^4.9.3", "webpack": "^5.74.0", "webpack-cli": "^4.9.2", "webpack-dev-server": "^4.11.1" }, "keywords": [ "webpack", "css", "extract", "hmr" ] } dist/plugin-options.json 0000755 00000005171 15075141406 0011403 0 ustar 00 { "title": "Mini CSS Extract Plugin options", "type": "object", "additionalProperties": false, "properties": { "filename": { "anyOf": [ { "type": "string", "absolutePath": false, "minLength": 1 }, { "instanceof": "Function" } ], "description": "This option determines the name of each output CSS file.", "link": "https://github.com/webpack-contrib/mini-css-extract-plugin#filename" }, "chunkFilename": { "anyOf": [ { "type": "string", "absolutePath": false, "minLength": 1 }, { "instanceof": "Function" } ], "description": "This option determines the name of non-entry chunk files.", "link": "https://github.com/webpack-contrib/mini-css-extract-plugin#chunkfilename" }, "experimentalUseImportModule": { "type": "boolean", "description": "Enable the experimental importModule approach instead of using child compilers. This uses less memory and is faster.", "link": "https://github.com/webpack-contrib/mini-css-extract-plugin#experimentaluseimportmodule" }, "ignoreOrder": { "type": "boolean", "description": "Remove Order Warnings.", "link": "https://github.com/webpack-contrib/mini-css-extract-plugin#ignoreorder" }, "insert": { "description": "Inserts the `link` tag at the given position for non-initial (async) (https://webpack.js.org/concepts/under-the-hood/#chunks) CSS chunks.", "link": "https://github.com/webpack-contrib/mini-css-extract-plugin#insert", "anyOf": [ { "type": "string" }, { "instanceof": "Function" } ] }, "attributes": { "description": "Adds custom attributes to the `link` tag for non-initial (async) (https://webpack.js.org/concepts/under-the-hood/#chunks) CSS chunks.", "link": "https://github.com/webpack-contrib/mini-css-extract-plugin#attributes", "type": "object" }, "linkType": { "anyOf": [ { "enum": ["text/css"] }, { "type": "boolean" } ], "description": "This option allows loading asynchronous chunks with a custom link type", "link": "https://github.com/webpack-contrib/mini-css-extract-plugin#linktype" }, "runtime": { "type": "boolean", "description": "Enabled/Disables runtime generation. CSS will be still extracted and can be used for a custom loading methods.", "link": "https://github.com/webpack-contrib/mini-css-extract-plugin#noRuntime" } } } dist/loader.js 0000755 00000030421 15075141406 0007321 0 ustar 00 "use strict"; const path = require("path"); const { findModuleById, evalModuleCode, AUTO_PUBLIC_PATH, ABSOLUTE_PUBLIC_PATH, BASE_URI, SINGLE_DOT_PATH_SEGMENT, stringifyRequest, stringifyLocal } = require("./utils"); const schema = require("./loader-options.json"); const MiniCssExtractPlugin = require("./index"); /** @typedef {import("schema-utils/declarations/validate").Schema} Schema */ /** @typedef {import("webpack").Compiler} Compiler */ /** @typedef {import("webpack").Compilation} Compilation */ /** @typedef {import("webpack").Chunk} Chunk */ /** @typedef {import("webpack").Module} Module */ /** @typedef {import("webpack").sources.Source} Source */ /** @typedef {import("webpack").AssetInfo} AssetInfo */ /** @typedef {import("webpack").NormalModule} NormalModule */ /** @typedef {import("./index.js").LoaderOptions} LoaderOptions */ /** @typedef {{ [key: string]: string | function }} Locals */ /** @typedef {any} TODO */ /** * @typedef {Object} Dependency * @property {string} identifier * @property {string | null} context * @property {Buffer} content * @property {string} media * @property {string} [supports] * @property {string} [layer] * @property {Buffer} [sourceMap] */ /** * @param {string} content * @param {{ loaderContext: import("webpack").LoaderContext<LoaderOptions>, options: LoaderOptions, locals: Locals | undefined }} context * @returns {string} */ function hotLoader(content, context) { const accept = context.locals ? "" : "module.hot.accept(undefined, cssReload);"; return `${content} if(module.hot) { // ${Date.now()} var cssReload = require(${stringifyRequest(context.loaderContext, path.join(__dirname, "hmr/hotModuleReplacement.js"))})(module.id, ${JSON.stringify({ ...context.options, locals: !!context.locals })}); module.hot.dispose(cssReload); ${accept} } `; } /** * @this {import("webpack").LoaderContext<LoaderOptions>} * @param {string} request */ function pitch(request) { // @ts-ignore const options = this.getOptions( /** @type {Schema} */schema); const emit = typeof options.emit !== "undefined" ? options.emit : true; const callback = this.async(); const optionsFromPlugin = /** @type {TODO} */this[MiniCssExtractPlugin.pluginSymbol]; if (!optionsFromPlugin) { callback(new Error("You forgot to add 'mini-css-extract-plugin' plugin (i.e. `{ plugins: [new MiniCssExtractPlugin()] }`), please read https://github.com/webpack-contrib/mini-css-extract-plugin#getting-started")); return; } const { webpack } = /** @type {Compiler} */this._compiler; /** * @param {TODO} originalExports * @param {Compilation} [compilation] * @param {{ [name: string]: Source }} [assets] * @param {Map<string, AssetInfo>} [assetsInfo] * @returns {void} */ const handleExports = (originalExports, compilation, assets, assetsInfo) => { /** @type {Locals | undefined} */ let locals; let namedExport; const esModule = typeof options.esModule !== "undefined" ? options.esModule : true; /** * @param {Dependency[] | [null, object][]} dependencies */ const addDependencies = dependencies => { if (!Array.isArray(dependencies) && dependencies != null) { throw new Error(`Exported value was not extracted as an array: ${JSON.stringify(dependencies)}`); } const identifierCountMap = new Map(); let lastDep; for (const dependency of dependencies) { if (! /** @type {Dependency} */dependency.identifier || !emit) { // eslint-disable-next-line no-continue continue; } const count = identifierCountMap.get( /** @type {Dependency} */dependency.identifier) || 0; const CssDependency = MiniCssExtractPlugin.getCssDependency(webpack); /** @type {NormalModule} */ this._module.addDependency(lastDep = new CssDependency( /** @type {Dependency} */ dependency, /** @type {Dependency} */ dependency.context, count)); identifierCountMap.set( /** @type {Dependency} */ dependency.identifier, count + 1); } if (lastDep && assets) { lastDep.assets = assets; lastDep.assetsInfo = assetsInfo; } }; try { // eslint-disable-next-line no-underscore-dangle const exports = originalExports.__esModule ? originalExports.default : originalExports; namedExport = // eslint-disable-next-line no-underscore-dangle originalExports.__esModule && (!originalExports.default || !("locals" in originalExports.default)); if (namedExport) { Object.keys(originalExports).forEach(key => { if (key !== "default") { if (!locals) { locals = {}; } /** @type {Locals} */ locals[key] = originalExports[key]; } }); } else { locals = exports && exports.locals; } /** @type {Dependency[] | [null, object][]} */ let dependencies; if (!Array.isArray(exports)) { dependencies = [[null, exports]]; } else { dependencies = exports.map(([id, content, media, sourceMap, supports, layer]) => { let identifier = id; let context; if (compilation) { const module = /** @type {Module} */ findModuleById(compilation, id); identifier = module.identifier(); ({ context } = module); } else { // TODO check if this context is used somewhere context = this.rootContext; } return { identifier, context, content: Buffer.from(content), media, supports, layer, sourceMap: sourceMap ? Buffer.from(JSON.stringify(sourceMap)) : // eslint-disable-next-line no-undefined undefined }; }); } addDependencies(dependencies); } catch (e) { callback( /** @type {Error} */e); return; } const result = locals ? namedExport ? Object.keys(locals).map(key => `\nexport var ${key} = ${stringifyLocal( /** @type {Locals} */locals[key])};`).join("") : `\n${esModule ? "export default" : "module.exports ="} ${JSON.stringify(locals)};` : esModule ? `\nexport {};` : ""; let resultSource = `// extracted by ${MiniCssExtractPlugin.pluginName}`; // only attempt hotreloading if the css is actually used for something other than hash values resultSource += this.hot && emit ? hotLoader(result, { loaderContext: this, options, locals }) : result; callback(null, resultSource); }; let { publicPath } = /** @type {Compilation} */ this._compilation.outputOptions; if (typeof options.publicPath === "string") { // eslint-disable-next-line prefer-destructuring publicPath = options.publicPath; } else if (typeof options.publicPath === "function") { publicPath = options.publicPath(this.resourcePath, this.rootContext); } if (publicPath === "auto") { publicPath = AUTO_PUBLIC_PATH; } if (typeof optionsFromPlugin.experimentalUseImportModule === "undefined" && typeof this.importModule === "function" || optionsFromPlugin.experimentalUseImportModule) { if (!this.importModule) { callback(new Error("You are using 'experimentalUseImportModule' but 'this.importModule' is not available in loader context. You need to have at least webpack 5.33.2.")); return; } let publicPathForExtract; if (typeof publicPath === "string") { const isAbsolutePublicPath = /^[a-zA-Z][a-zA-Z\d+\-.]*?:/.test(publicPath); publicPathForExtract = isAbsolutePublicPath ? publicPath : `${ABSOLUTE_PUBLIC_PATH}${publicPath.replace(/\./g, SINGLE_DOT_PATH_SEGMENT)}`; } else { publicPathForExtract = publicPath; } this.importModule(`${this.resourcePath}.webpack[javascript/auto]!=!!!${request}`, { layer: options.layer, publicPath: /** @type {string} */publicPathForExtract, baseUri: `${BASE_URI}/` }, /** * @param {Error | null | undefined} error * @param {object} exports */ (error, exports) => { if (error) { callback(error); return; } handleExports(exports); }); return; } const loaders = this.loaders.slice(this.loaderIndex + 1); this.addDependency(this.resourcePath); const childFilename = "*"; const outputOptions = { filename: childFilename, publicPath }; const childCompiler = /** @type {Compilation} */ this._compilation.createChildCompiler(`${MiniCssExtractPlugin.pluginName} ${request}`, outputOptions); // The templates are compiled and executed by NodeJS - similar to server side rendering // Unfortunately this causes issues as some loaders require an absolute URL to support ES Modules // The following config enables relative URL support for the child compiler childCompiler.options.module = { ...childCompiler.options.module }; childCompiler.options.module.parser = { ...childCompiler.options.module.parser }; childCompiler.options.module.parser.javascript = { ...childCompiler.options.module.parser.javascript, url: "relative" }; const { NodeTemplatePlugin } = webpack.node; const { NodeTargetPlugin } = webpack.node; new NodeTemplatePlugin(outputOptions).apply(childCompiler); new NodeTargetPlugin().apply(childCompiler); const { EntryOptionPlugin } = webpack; const { library: { EnableLibraryPlugin } } = webpack; new EnableLibraryPlugin("commonjs2").apply(childCompiler); EntryOptionPlugin.applyEntryOption(childCompiler, this.context, { child: { library: { type: "commonjs2" }, import: [`!!${request}`] } }); const { LimitChunkCountPlugin } = webpack.optimize; new LimitChunkCountPlugin({ maxChunks: 1 }).apply(childCompiler); const { NormalModule } = webpack; childCompiler.hooks.thisCompilation.tap(`${MiniCssExtractPlugin.pluginName} loader`, /** * @param {Compilation} compilation */ compilation => { const normalModuleHook = NormalModule.getCompilationHooks(compilation).loader; normalModuleHook.tap(`${MiniCssExtractPlugin.pluginName} loader`, (loaderContext, module) => { if (module.request === request) { // eslint-disable-next-line no-param-reassign module.loaders = loaders.map(loader => { return { type: null, loader: loader.path, options: loader.options, ident: loader.ident }; }); } }); }); /** @type {string | Buffer} */ let source; childCompiler.hooks.compilation.tap(MiniCssExtractPlugin.pluginName, /** * @param {Compilation} compilation */ compilation => { compilation.hooks.processAssets.tap(MiniCssExtractPlugin.pluginName, () => { source = compilation.assets[childFilename] && compilation.assets[childFilename].source(); // Remove all chunk assets compilation.chunks.forEach(chunk => { chunk.files.forEach(file => { compilation.deleteAsset(file); }); }); }); }); childCompiler.runAsChild((error, entries, compilation) => { if (error) { callback(error); return; } if ( /** @type {Compilation} */compilation.errors.length > 0) { callback( /** @type {Compilation} */compilation.errors[0]); return; } /** @type {{ [name: string]: Source }} */ const assets = Object.create(null); /** @type {Map<string, AssetInfo>} */ const assetsInfo = new Map(); for (const asset of /** @type {Compilation} */compilation.getAssets()) { assets[asset.name] = asset.source; assetsInfo.set(asset.name, asset.info); } /** @type {Compilation} */ compilation.fileDependencies.forEach(dep => { this.addDependency(dep); }, this); /** @type {Compilation} */ compilation.contextDependencies.forEach(dep => { this.addContextDependency(dep); }, this); if (!source) { callback(new Error("Didn't get a result from child compiler")); return; } let originalExports; try { originalExports = evalModuleCode(this, source, request); } catch (e) { callback( /** @type {Error} */e); return; } handleExports(originalExports, compilation, assets, assetsInfo); }); } module.exports = { default: function loader() {}, pitch }; dist/hmr/hotModuleReplacement.js 0000755 00000011767 15075141406 0012775 0 ustar 00 "use strict"; /* eslint-env browser */ /* eslint-disable no-console, func-names */ /** @typedef {any} TODO */ var normalizeUrl = require("./normalize-url"); var srcByModuleId = Object.create(null); var noDocument = typeof document === "undefined"; var forEach = Array.prototype.forEach; /** * @param {function} fn * @param {number} time * @returns {(function(): void)|*} */ function debounce(fn, time) { var timeout = 0; return function () { // @ts-ignore var self = this; // eslint-disable-next-line prefer-rest-params var args = arguments; var functionCall = function functionCall() { return fn.apply(self, args); }; clearTimeout(timeout); // @ts-ignore timeout = setTimeout(functionCall, time); }; } function noop() {} /** * @param {TODO} moduleId * @returns {TODO} */ function getCurrentScriptUrl(moduleId) { var src = srcByModuleId[moduleId]; if (!src) { if (document.currentScript) { src = /** @type {HTMLScriptElement} */document.currentScript.src; } else { var scripts = document.getElementsByTagName("script"); var lastScriptTag = scripts[scripts.length - 1]; if (lastScriptTag) { src = lastScriptTag.src; } } srcByModuleId[moduleId] = src; } /** * @param {string} fileMap * @returns {null | string[]} */ return function (fileMap) { if (!src) { return null; } var splitResult = src.split(/([^\\/]+)\.js$/); var filename = splitResult && splitResult[1]; if (!filename) { return [src.replace(".js", ".css")]; } if (!fileMap) { return [src.replace(".js", ".css")]; } return fileMap.split(",").map(function (mapRule) { var reg = new RegExp("".concat(filename, "\\.js$"), "g"); return normalizeUrl(src.replace(reg, "".concat(mapRule.replace(/{fileName}/g, filename), ".css"))); }); }; } /** * @param {TODO} el * @param {string} [url] */ function updateCss(el, url) { if (!url) { if (!el.href) { return; } // eslint-disable-next-line url = el.href.split("?")[0]; } if (!isUrlRequest( /** @type {string} */url)) { return; } if (el.isLoaded === false) { // We seem to be about to replace a css link that hasn't loaded yet. // We're probably changing the same file more than once. return; } if (!url || !(url.indexOf(".css") > -1)) { return; } // eslint-disable-next-line no-param-reassign el.visited = true; var newEl = el.cloneNode(); newEl.isLoaded = false; newEl.addEventListener("load", function () { if (newEl.isLoaded) { return; } newEl.isLoaded = true; el.parentNode.removeChild(el); }); newEl.addEventListener("error", function () { if (newEl.isLoaded) { return; } newEl.isLoaded = true; el.parentNode.removeChild(el); }); newEl.href = "".concat(url, "?").concat(Date.now()); if (el.nextSibling) { el.parentNode.insertBefore(newEl, el.nextSibling); } else { el.parentNode.appendChild(newEl); } } /** * @param {string} href * @param {TODO} src * @returns {TODO} */ function getReloadUrl(href, src) { var ret; // eslint-disable-next-line no-param-reassign href = normalizeUrl(href); src.some( /** * @param {string} url */ // eslint-disable-next-line array-callback-return function (url) { if (href.indexOf(src) > -1) { ret = url; } }); return ret; } /** * @param {string} [src] * @returns {boolean} */ function reloadStyle(src) { if (!src) { return false; } var elements = document.querySelectorAll("link"); var loaded = false; forEach.call(elements, function (el) { if (!el.href) { return; } var url = getReloadUrl(el.href, src); if (!isUrlRequest(url)) { return; } if (el.visited === true) { return; } if (url) { updateCss(el, url); loaded = true; } }); return loaded; } function reloadAll() { var elements = document.querySelectorAll("link"); forEach.call(elements, function (el) { if (el.visited === true) { return; } updateCss(el); }); } /** * @param {string} url * @returns {boolean} */ function isUrlRequest(url) { // An URL is not an request if // It is not http or https if (!/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(url)) { return false; } return true; } /** * @param {TODO} moduleId * @param {TODO} options * @returns {TODO} */ module.exports = function (moduleId, options) { if (noDocument) { console.log("no window.document found, will not HMR CSS"); return noop; } var getScriptSrc = getCurrentScriptUrl(moduleId); function update() { var src = getScriptSrc(options.filename); var reloaded = reloadStyle(src); if (options.locals) { console.log("[HMR] Detected local css modules. Reload all css"); reloadAll(); return; } if (reloaded) { console.log("[HMR] css reload %s", src.join(" ")); } else { console.log("[HMR] Reload all css"); reloadAll(); } } return debounce(update, 50); }; dist/hmr/normalize-url.js 0000755 00000001671 15075141406 0011446 0 ustar 00 "use strict"; /* eslint-disable */ /** * @param {string[]} pathComponents * @returns {string} */ function normalizeUrl(pathComponents) { return pathComponents.reduce(function (accumulator, item) { switch (item) { case "..": accumulator.pop(); break; case ".": break; default: accumulator.push(item); } return accumulator; }, /** @type {string[]} */[]).join("/"); } /** * @param {string} urlString * @returns {string} */ module.exports = function (urlString) { urlString = urlString.trim(); if (/^data:/i.test(urlString)) { return urlString; } var protocol = urlString.indexOf("//") !== -1 ? urlString.split("//")[0] + "//" : ""; var components = urlString.replace(new RegExp(protocol, "i"), "").split("/"); var host = components[0].toLowerCase().replace(/\.$/, ""); components[0] = ""; var path = normalizeUrl(components); return protocol + host + path; }; dist/loader-options.json 0000755 00000001777 15075141406 0011363 0 ustar 00 { "title": "Mini CSS Extract Plugin Loader options", "type": "object", "additionalProperties": false, "properties": { "publicPath": { "anyOf": [ { "type": "string" }, { "instanceof": "Function" } ], "description": "Specifies a custom public path for the external resources like images, files, etc inside CSS.", "link": "https://github.com/webpack-contrib/mini-css-extract-plugin#publicpath" }, "emit": { "type": "boolean", "description": "If true, emits a file (writes a file to the filesystem). If false, the plugin will extract the CSS but will not emit the file", "link": "https://github.com/webpack-contrib/mini-css-extract-plugin#emit" }, "esModule": { "type": "boolean", "description": "Generates JS modules that use the ES modules syntax.", "link": "https://github.com/webpack-contrib/mini-css-extract-plugin#esmodule" }, "layer": { "type": "string" } } } dist/utils.js 0000755 00000012533 15075141406 0007217 0 ustar 00 "use strict"; const NativeModule = require("module"); const path = require("path"); /** @typedef {import("webpack").Compilation} Compilation */ /** @typedef {import("webpack").Module} Module */ /** @typedef {import("webpack").LoaderContext<any>} LoaderContext */ /** * @returns {boolean} */ function trueFn() { return true; } /** * @param {Compilation} compilation * @param {string | number} id * @returns {null | Module} */ function findModuleById(compilation, id) { const { modules, chunkGraph } = compilation; for (const module of modules) { const moduleId = typeof chunkGraph !== "undefined" ? chunkGraph.getModuleId(module) : module.id; if (moduleId === id) { return module; } } return null; } /** * @param {LoaderContext} loaderContext * @param {string | Buffer} code * @param {string} filename * @returns {object} */ function evalModuleCode(loaderContext, code, filename) { // @ts-ignore const module = new NativeModule(filename, loaderContext); // @ts-ignore module.paths = NativeModule._nodeModulePaths(loaderContext.context); // eslint-disable-line no-underscore-dangle module.filename = filename; // @ts-ignore module._compile(code, filename); // eslint-disable-line no-underscore-dangle return module.exports; } /** * @param {string} a * @param {string} b * @returns {0 | 1 | -1} */ function compareIds(a, b) { if (typeof a !== typeof b) { return typeof a < typeof b ? -1 : 1; } if (a < b) { return -1; } if (a > b) { return 1; } return 0; } /** * @param {Module} a * @param {Module} b * @returns {0 | 1 | -1} */ function compareModulesByIdentifier(a, b) { return compareIds(a.identifier(), b.identifier()); } const MODULE_TYPE = "css/mini-extract"; const AUTO_PUBLIC_PATH = "__mini_css_extract_plugin_public_path_auto__"; const ABSOLUTE_PUBLIC_PATH = "webpack:///mini-css-extract-plugin/"; const BASE_URI = "webpack://"; const SINGLE_DOT_PATH_SEGMENT = "__mini_css_extract_plugin_single_dot_path_segment__"; /** * @param {string} str * @returns {boolean} */ function isAbsolutePath(str) { return path.posix.isAbsolute(str) || path.win32.isAbsolute(str); } const RELATIVE_PATH_REGEXP = /^\.\.?[/\\]/; /** * @param {string} str * @returns {boolean} */ function isRelativePath(str) { return RELATIVE_PATH_REGEXP.test(str); } // TODO simplify for the next major release /** * @param {LoaderContext} loaderContext * @param {string} request * @returns {string} */ function stringifyRequest(loaderContext, request) { if (typeof loaderContext.utils !== "undefined" && typeof loaderContext.utils.contextify === "function") { return JSON.stringify(loaderContext.utils.contextify(loaderContext.context || loaderContext.rootContext, request)); } const splitted = request.split("!"); const { context } = loaderContext; return JSON.stringify(splitted.map(part => { // First, separate singlePath from query, because the query might contain paths again const splittedPart = part.match(/^(.*?)(\?.*)/); const query = splittedPart ? splittedPart[2] : ""; let singlePath = splittedPart ? splittedPart[1] : part; if (isAbsolutePath(singlePath) && context) { singlePath = path.relative(context, singlePath); if (isAbsolutePath(singlePath)) { // If singlePath still matches an absolute path, singlePath was on a different drive than context. // In this case, we leave the path platform-specific without replacing any separators. // @see https://github.com/webpack/loader-utils/pull/14 return singlePath + query; } if (isRelativePath(singlePath) === false) { // Ensure that the relative path starts at least with ./ otherwise it would be a request into the modules directory (like node_modules). singlePath = `./${singlePath}`; } } return singlePath.replace(/\\/g, "/") + query; }).join("!")); } /** * @param {string} filename * @param {string} outputPath * @param {boolean} enforceRelative * @returns {string} */ function getUndoPath(filename, outputPath, enforceRelative) { let depth = -1; let append = ""; // eslint-disable-next-line no-param-reassign outputPath = outputPath.replace(/[\\/]$/, ""); for (const part of filename.split(/[/\\]+/)) { if (part === "..") { if (depth > -1) { // eslint-disable-next-line no-plusplus depth--; } else { const i = outputPath.lastIndexOf("/"); const j = outputPath.lastIndexOf("\\"); const pos = i < 0 ? j : j < 0 ? i : Math.max(i, j); if (pos < 0) { return `${outputPath}/`; } append = `${outputPath.slice(pos + 1)}/${append}`; // eslint-disable-next-line no-param-reassign outputPath = outputPath.slice(0, pos); } } else if (part !== ".") { // eslint-disable-next-line no-plusplus depth++; } } return depth > 0 ? `${"../".repeat(depth)}${append}` : enforceRelative ? `./${append}` : append; } /** * * @param {string | function} value * @returns {string} */ function stringifyLocal(value) { return typeof value === "function" ? value.toString() : JSON.stringify(value); } module.exports = { trueFn, findModuleById, evalModuleCode, compareModulesByIdentifier, MODULE_TYPE, AUTO_PUBLIC_PATH, ABSOLUTE_PUBLIC_PATH, BASE_URI, SINGLE_DOT_PATH_SEGMENT, stringifyRequest, stringifyLocal, getUndoPath }; dist/index.js 0000755 00000116266 15075141406 0007176 0 ustar 00 "use strict"; /* eslint-disable class-methods-use-this */ const path = require("path"); const { validate } = require("schema-utils"); const schema = require("./plugin-options.json"); const { trueFn, MODULE_TYPE, AUTO_PUBLIC_PATH, ABSOLUTE_PUBLIC_PATH, SINGLE_DOT_PATH_SEGMENT, compareModulesByIdentifier, getUndoPath, BASE_URI } = require("./utils"); /** @typedef {import("schema-utils/declarations/validate").Schema} Schema */ /** @typedef {import("webpack").Compiler} Compiler */ /** @typedef {import("webpack").Compilation} Compilation */ /** @typedef {import("webpack").ChunkGraph} ChunkGraph */ /** @typedef {import("webpack").Chunk} Chunk */ /** @typedef {Parameters<import("webpack").Chunk["isInGroup"]>[0]} ChunkGroup */ /** @typedef {import("webpack").Module} Module */ /** @typedef {import("webpack").Dependency} Dependency */ /** @typedef {import("webpack").sources.Source} Source */ /** @typedef {import("webpack").Configuration} Configuration */ /** @typedef {import("webpack").WebpackError} WebpackError */ /** @typedef {import("webpack").AssetInfo} AssetInfo */ /** @typedef {import("./loader.js").Dependency} LoaderDependency */ /** * @typedef {Object} LoaderOptions * @property {string | ((resourcePath: string, rootContext: string) => string)} [publicPath] * @property {boolean} [emit] * @property {boolean} [esModule] * @property {string} [layer] */ /** * @typedef {Object} PluginOptions * @property {Required<Configuration>['output']['filename']} [filename] * @property {Required<Configuration>['output']['chunkFilename']} [chunkFilename] * @property {boolean} [ignoreOrder] * @property {string | ((linkTag: HTMLLinkElement) => void)} [insert] * @property {Record<string, string>} [attributes] * @property {string | false | 'text/css'} [linkType] * @property {boolean} [runtime] * @property {boolean} [experimentalUseImportModule] */ /** * @typedef {Object} NormalizedPluginOptions * @property {Required<Configuration>['output']['filename']} filename * @property {Required<Configuration>['output']['chunkFilename']} [chunkFilename] * @property {boolean} ignoreOrder * @property {string | ((linkTag: HTMLLinkElement) => void)} [insert] * @property {Record<string, string>} [attributes] * @property {string | false | 'text/css'} [linkType] * @property {boolean} runtime * @property {boolean} [experimentalUseImportModule] */ /** * @typedef {Object} RuntimeOptions * @property {string | ((linkTag: HTMLLinkElement) => void) | undefined} insert * @property {string | false | 'text/css'} linkType * @property {Record<string, string> | undefined} attributes */ /** @typedef {any} TODO */ const pluginName = "mini-css-extract-plugin"; const pluginSymbol = Symbol(pluginName); const DEFAULT_FILENAME = "[name].css"; /** * @type {Set<string>} */ const TYPES = new Set([MODULE_TYPE]); /** * @type {ReturnType<Module["codeGeneration"]>} */ const CODE_GENERATION_RESULT = { sources: new Map(), runtimeRequirements: new Set() }; /** @typedef {Module & { content: Buffer, media?: string, sourceMap?: Buffer, supports?: string, layer?: string, assets?: { [key: string]: TODO }, assetsInfo?: Map<string, AssetInfo> }} CssModule */ /** @typedef {{ context: string | null, identifier: string, identifierIndex: number, content: Buffer, sourceMap?: Buffer, media?: string, supports?: string, layer?: TODO, assetsInfo?: Map<string, AssetInfo>, assets?: { [key: string]: TODO }}} CssModuleDependency */ /** @typedef {{ new(dependency: CssModuleDependency): CssModule }} CssModuleConstructor */ /** @typedef {Dependency & CssModuleDependency} CssDependency */ /** @typedef {Omit<LoaderDependency, "context">} CssDependencyOptions */ /** @typedef {{ new(loaderDependency: CssDependencyOptions, context: string | null, identifierIndex: number): CssDependency }} CssDependencyConstructor */ /** * * @type {WeakMap<Compiler["webpack"], CssModuleConstructor>} */ const cssModuleCache = new WeakMap(); /** * @type {WeakMap<Compiler["webpack"], CssDependencyConstructor>} */ const cssDependencyCache = new WeakMap(); /** * @type {WeakSet<Compiler["webpack"]>} */ const registered = new WeakSet(); class MiniCssExtractPlugin { /** * @param {Compiler["webpack"]} webpack * @returns {CssModuleConstructor} */ static getCssModule(webpack) { /** * Prevent creation of multiple CssModule classes to allow other integrations to get the current CssModule. */ if (cssModuleCache.has(webpack)) { return (/** @type {CssModuleConstructor} */cssModuleCache.get(webpack) ); } class CssModule extends webpack.Module { /** * @param {CssModuleDependency} dependency */ constructor({ context, identifier, identifierIndex, content, layer, supports, media, sourceMap, assets, assetsInfo }) { super(MODULE_TYPE, /** @type {string | undefined} */context); this.id = ""; this._context = context; this._identifier = identifier; this._identifierIndex = identifierIndex; this.content = content; this.layer = layer; this.supports = supports; this.media = media; this.sourceMap = sourceMap; this.assets = assets; this.assetsInfo = assetsInfo; this._needBuild = true; } // no source() so webpack 4 doesn't do add stuff to the bundle size() { return this.content.length; } identifier() { return `css|${this._identifier}|${this._identifierIndex}`; } /** * @param {Parameters<Module["readableIdentifier"]>[0]} requestShortener * @returns {ReturnType<Module["readableIdentifier"]>} */ readableIdentifier(requestShortener) { return `css ${requestShortener.shorten(this._identifier)}${this._identifierIndex ? ` (${this._identifierIndex})` : ""}`; } // eslint-disable-next-line class-methods-use-this getSourceTypes() { return TYPES; } // eslint-disable-next-line class-methods-use-this codeGeneration() { return CODE_GENERATION_RESULT; } nameForCondition() { const resource = /** @type {string} */ this._identifier.split("!").pop(); const idx = resource.indexOf("?"); if (idx >= 0) { return resource.substring(0, idx); } return resource; } /** * @param {Module} module */ updateCacheModule(module) { if (this.content !== /** @type {CssModule} */module.content || this.layer !== /** @type {CssModule} */module.layer || this.supports !== /** @type {CssModule} */module.supports || this.media !== /** @type {CssModule} */module.media || this.sourceMap !== /** @type {CssModule} */module.sourceMap || this.assets !== /** @type {CssModule} */module.assets || this.assetsInfo !== /** @type {CssModule} */module.assetsInfo) { this._needBuild = true; this.content = /** @type {CssModule} */module.content; this.layer = /** @type {CssModule} */module.layer; this.supports = /** @type {CssModule} */module.supports; this.media = /** @type {CssModule} */module.media; this.sourceMap = /** @type {CssModule} */module.sourceMap; this.assets = /** @type {CssModule} */module.assets; this.assetsInfo = /** @type {CssModule} */module.assetsInfo; } } // eslint-disable-next-line class-methods-use-this needRebuild() { return this._needBuild; } // eslint-disable-next-line class-methods-use-this /** * @param {Parameters<Module["needBuild"]>[0]} context context info * @param {Parameters<Module["needBuild"]>[1]} callback callback function, returns true, if the module needs a rebuild */ needBuild(context, callback) { // eslint-disable-next-line no-undefined callback(undefined, this._needBuild); } /** * @param {Parameters<Module["build"]>[0]} options * @param {Parameters<Module["build"]>[1]} compilation * @param {Parameters<Module["build"]>[2]} resolver * @param {Parameters<Module["build"]>[3]} fileSystem * @param {Parameters<Module["build"]>[4]} callback */ build(options, compilation, resolver, fileSystem, callback) { this.buildInfo = { assets: this.assets, assetsInfo: this.assetsInfo, cacheable: true, hash: this._computeHash( /** @type {string} */compilation.outputOptions.hashFunction) }; this.buildMeta = {}; this._needBuild = false; callback(); } /** * @private * @param {string} hashFunction * @returns {string | Buffer} */ _computeHash(hashFunction) { const hash = webpack.util.createHash(hashFunction); hash.update(this.content); if (this.layer) { hash.update(this.layer); } hash.update(this.supports || ""); hash.update(this.media || ""); hash.update(this.sourceMap || ""); return hash.digest("hex"); } /** * @param {Parameters<Module["updateHash"]>[0]} hash * @param {Parameters<Module["updateHash"]>[1]} context */ updateHash(hash, context) { super.updateHash(hash, context); hash.update(this.buildInfo.hash); } /** * @param {Parameters<Module["serialize"]>[0]} context */ serialize(context) { const { write } = context; write(this._context); write(this._identifier); write(this._identifierIndex); write(this.content); write(this.layer); write(this.supports); write(this.media); write(this.sourceMap); write(this.assets); write(this.assetsInfo); write(this._needBuild); super.serialize(context); } /** * @param {Parameters<Module["deserialize"]>[0]} context */ deserialize(context) { this._needBuild = context.read(); super.deserialize(context); } } cssModuleCache.set(webpack, CssModule); webpack.util.serialization.register(CssModule, path.resolve(__dirname, "CssModule"), // @ts-ignore null, { serialize(instance, context) { instance.serialize(context); }, deserialize(context) { const { read } = context; const contextModule = read(); const identifier = read(); const identifierIndex = read(); const content = read(); const layer = read(); const supports = read(); const media = read(); const sourceMap = read(); const assets = read(); const assetsInfo = read(); const dep = new CssModule({ context: contextModule, identifier, identifierIndex, content, layer, supports, media, sourceMap, assets, assetsInfo }); dep.deserialize(context); return dep; } }); return CssModule; } /** * @param {Compiler["webpack"]} webpack * @returns {CssDependencyConstructor} */ static getCssDependency(webpack) { /** * Prevent creation of multiple CssDependency classes to allow other integrations to get the current CssDependency. */ if (cssDependencyCache.has(webpack)) { return (/** @type {CssDependencyConstructor} */ cssDependencyCache.get(webpack) ); } class CssDependency extends webpack.Dependency { /** * @param {CssDependencyOptions} loaderDependency * @param {string | null} context * @param {number} identifierIndex */ constructor({ identifier, content, layer, supports, media, sourceMap }, context, identifierIndex) { super(); this.identifier = identifier; this.identifierIndex = identifierIndex; this.content = content; this.layer = layer; this.supports = supports; this.media = media; this.sourceMap = sourceMap; this.context = context; /** @type {{ [key: string]: Source } | undefined}} */ // eslint-disable-next-line no-undefined this.assets = undefined; /** @type {Map<string, AssetInfo> | undefined} */ // eslint-disable-next-line no-undefined this.assetsInfo = undefined; } /** * @returns {ReturnType<Dependency["getResourceIdentifier"]>} */ getResourceIdentifier() { return `css-module-${this.identifier}-${this.identifierIndex}`; } /** * @returns {ReturnType<Dependency["getModuleEvaluationSideEffectsState"]>} */ // eslint-disable-next-line class-methods-use-this getModuleEvaluationSideEffectsState() { return webpack.ModuleGraphConnection.TRANSITIVE_ONLY; } /** * @param {Parameters<Dependency["serialize"]>[0]} context */ serialize(context) { const { write } = context; write(this.identifier); write(this.content); write(this.layer); write(this.supports); write(this.media); write(this.sourceMap); write(this.context); write(this.identifierIndex); write(this.assets); write(this.assetsInfo); super.serialize(context); } /** * @param {Parameters<Dependency["deserialize"]>[0]} context */ deserialize(context) { super.deserialize(context); } } cssDependencyCache.set(webpack, CssDependency); webpack.util.serialization.register(CssDependency, path.resolve(__dirname, "CssDependency"), // @ts-ignore null, { serialize(instance, context) { instance.serialize(context); }, deserialize(context) { const { read } = context; const dep = new CssDependency({ identifier: read(), content: read(), layer: read(), supports: read(), media: read(), sourceMap: read() }, read(), read()); const assets = read(); const assetsInfo = read(); dep.assets = assets; dep.assetsInfo = assetsInfo; dep.deserialize(context); return dep; } }); return CssDependency; } /** * @param {PluginOptions} [options] */ constructor(options = {}) { validate( /** @type {Schema} */schema, options, { baseDataPath: "options" }); /** * @private * @type {WeakMap<Chunk, Set<CssModule>>} * @private */ this._sortedModulesCache = new WeakMap(); /** * @private * @type {NormalizedPluginOptions} */ this.options = Object.assign({ filename: DEFAULT_FILENAME, ignoreOrder: false, // TODO remove in the next major release // eslint-disable-next-line no-undefined experimentalUseImportModule: undefined, runtime: true }, options); /** * @private * @type {RuntimeOptions} */ this.runtimeOptions = { insert: options.insert, linkType: // Todo in next major release set default to "false" typeof options.linkType === "boolean" && /** @type {boolean} */options.linkType === true || typeof options.linkType === "undefined" ? "text/css" : options.linkType, attributes: options.attributes }; if (!this.options.chunkFilename) { const { filename } = this.options; if (typeof filename !== "function") { const hasName = /** @type {string} */filename.includes("[name]"); const hasId = /** @type {string} */filename.includes("[id]"); const hasChunkHash = /** @type {string} */ filename.includes("[chunkhash]"); const hasContentHash = /** @type {string} */ filename.includes("[contenthash]"); // Anything changing depending on chunk is fine if (hasChunkHash || hasContentHash || hasName || hasId) { this.options.chunkFilename = filename; } else { // Otherwise prefix "[id]." in front of the basename to make it changing this.options.chunkFilename = /** @type {string} */ filename.replace(/(^|\/)([^/]*(?:\?|$))/, "$1[id].$2"); } } else { this.options.chunkFilename = "[id].css"; } } } /** * @param {Compiler} compiler */ apply(compiler) { const { webpack } = compiler; if (this.options.experimentalUseImportModule) { if (typeof /** @type {Compiler["options"]["experiments"] & { executeModule?: boolean }} */ compiler.options.experiments.executeModule === "undefined") { /** @type {Compiler["options"]["experiments"] & { executeModule?: boolean }} */ // eslint-disable-next-line no-param-reassign compiler.options.experiments.executeModule = true; } } // TODO bug in webpack, remove it after it will be fixed // webpack tries to `require` loader firstly when serializer doesn't found if (!registered.has(webpack)) { registered.add(webpack); webpack.util.serialization.registerLoader(/^mini-css-extract-plugin\//, trueFn); } const { splitChunks } = compiler.options.optimization; if (splitChunks) { if ( /** @type {string[]} */splitChunks.defaultSizeTypes.includes("...")) { /** @type {string[]} */ splitChunks.defaultSizeTypes.push(MODULE_TYPE); } } const CssModule = MiniCssExtractPlugin.getCssModule(webpack); const CssDependency = MiniCssExtractPlugin.getCssDependency(webpack); const { NormalModule } = compiler.webpack; compiler.hooks.compilation.tap(pluginName, compilation => { const { loader: normalModuleHook } = NormalModule.getCompilationHooks(compilation); normalModuleHook.tap(pluginName, /** * @param {object} loaderContext */ loaderContext => { /** @type {object & { [pluginSymbol]: { experimentalUseImportModule: boolean | undefined } }} */ // eslint-disable-next-line no-param-reassign loaderContext[pluginSymbol] = { experimentalUseImportModule: this.options.experimentalUseImportModule }; }); }); compiler.hooks.thisCompilation.tap(pluginName, compilation => { class CssModuleFactory { /** * @param {{ dependencies: Dependency[] }} dependencies * @param {(arg0?: Error, arg1?: TODO) => void} callback */ // eslint-disable-next-line class-methods-use-this create({ dependencies: [dependency] }, callback) { callback( // eslint-disable-next-line no-undefined undefined, new CssModule( /** @type {CssDependency} */dependency)); } } compilation.dependencyFactories.set(CssDependency, new CssModuleFactory()); class CssDependencyTemplate { // eslint-disable-next-line class-methods-use-this apply() {} } compilation.dependencyTemplates.set(CssDependency, new CssDependencyTemplate()); compilation.hooks.renderManifest.tap(pluginName, /** * @param {ReturnType<Compilation["getRenderManifest"]>} result * @param {Parameters<Compilation["getRenderManifest"]>[0]} chunk * @returns {TODO} */ (result, { chunk }) => { const { chunkGraph } = compilation; const { HotUpdateChunk } = webpack; // We don't need hot update chunks for css // We will use the real asset instead to update if (chunk instanceof HotUpdateChunk) { return; } /** @type {CssModule[]} */ const renderedModules = Array.from( /** @type {CssModule[]} */ this.getChunkModules(chunk, chunkGraph)).filter(module => module.type === MODULE_TYPE); const filenameTemplate = /** @type {string} */ chunk.canBeInitial() ? this.options.filename : this.options.chunkFilename; if (renderedModules.length > 0) { result.push({ render: () => this.renderContentAsset(compiler, compilation, chunk, renderedModules, compilation.runtimeTemplate.requestShortener, filenameTemplate, { contentHashType: MODULE_TYPE, chunk }), filenameTemplate, pathOptions: { chunk, contentHashType: MODULE_TYPE }, identifier: `${pluginName}.${chunk.id}`, hash: chunk.contentHash[MODULE_TYPE] }); } }); compilation.hooks.contentHash.tap(pluginName, chunk => { const { outputOptions, chunkGraph } = compilation; const modules = this.sortModules(compilation, chunk, /** @type {CssModule[]} */ chunkGraph.getChunkModulesIterableBySourceType(chunk, MODULE_TYPE), compilation.runtimeTemplate.requestShortener); if (modules) { const { hashFunction, hashDigest, hashDigestLength } = outputOptions; const { createHash } = compiler.webpack.util; const hash = createHash( /** @type {string} */hashFunction); for (const m of modules) { hash.update(chunkGraph.getModuleHash(m, chunk.runtime)); } // eslint-disable-next-line no-param-reassign chunk.contentHash[MODULE_TYPE] = /** @type {string} */ hash.digest(hashDigest).substring(0, hashDigestLength); } }); // All the code below is dedicated to the runtime and can be skipped when the `runtime` option is `false` if (!this.options.runtime) { return; } const { Template, RuntimeGlobals, RuntimeModule, runtime } = webpack; /** * @param {Chunk} mainChunk * @param {Compilation} compilation * @returns {Record<string, number>} */ // eslint-disable-next-line no-shadow const getCssChunkObject = (mainChunk, compilation) => { /** @type {Record<string, number>} */ const obj = {}; const { chunkGraph } = compilation; for (const chunk of mainChunk.getAllAsyncChunks()) { const modules = chunkGraph.getOrderedChunkModulesIterable(chunk, compareModulesByIdentifier); for (const module of modules) { if (module.type === MODULE_TYPE) { obj[/** @type {string} */chunk.id] = 1; break; } } } return obj; }; class CssLoadingRuntimeModule extends RuntimeModule { /** * @param {Set<string>} runtimeRequirements * @param {RuntimeOptions} runtimeOptions */ constructor(runtimeRequirements, runtimeOptions) { super("css loading", 10); this.runtimeRequirements = runtimeRequirements; this.runtimeOptions = runtimeOptions; } generate() { const { chunk, runtimeRequirements } = this; const { runtimeTemplate, outputOptions: { crossOriginLoading } } = this.compilation; const chunkMap = getCssChunkObject(chunk, this.compilation); const withLoading = runtimeRequirements.has(RuntimeGlobals.ensureChunkHandlers) && Object.keys(chunkMap).length > 0; const withHmr = runtimeRequirements.has(RuntimeGlobals.hmrDownloadUpdateHandlers); if (!withLoading && !withHmr) { return ""; } return Template.asString(['if (typeof document === "undefined") return;', `var createStylesheet = ${runtimeTemplate.basicFunction("chunkId, fullhref, oldTag, resolve, reject", ['var linkTag = document.createElement("link");', this.runtimeOptions.attributes ? Template.asString(Object.entries(this.runtimeOptions.attributes).map(entry => { const [key, value] = entry; return `linkTag.setAttribute(${JSON.stringify(key)}, ${JSON.stringify(value)});`; })) : "", 'linkTag.rel = "stylesheet";', this.runtimeOptions.linkType ? `linkTag.type = ${JSON.stringify(this.runtimeOptions.linkType)};` : "", `var onLinkComplete = ${runtimeTemplate.basicFunction("event", ["// avoid mem leaks.", "linkTag.onerror = linkTag.onload = null;", "if (event.type === 'load') {", Template.indent(["resolve();"]), "} else {", Template.indent(["var errorType = event && (event.type === 'load' ? 'missing' : event.type);", "var realHref = event && event.target && event.target.href || fullhref;", 'var err = new Error("Loading CSS chunk " + chunkId + " failed.\\n(" + realHref + ")");', 'err.code = "CSS_CHUNK_LOAD_FAILED";', "err.type = errorType;", "err.request = realHref;", "linkTag.parentNode.removeChild(linkTag)", "reject(err);"]), "}"])}`, "linkTag.onerror = linkTag.onload = onLinkComplete;", "linkTag.href = fullhref;", crossOriginLoading ? Template.asString([`if (linkTag.href.indexOf(window.location.origin + '/') !== 0) {`, Template.indent(`linkTag.crossOrigin = ${JSON.stringify(crossOriginLoading)};`), "}"]) : "", typeof this.runtimeOptions.insert !== "undefined" ? typeof this.runtimeOptions.insert === "function" ? `(${this.runtimeOptions.insert.toString()})(linkTag)` : Template.asString([`var target = document.querySelector("${this.runtimeOptions.insert}");`, `target.parentNode.insertBefore(linkTag, target.nextSibling);`]) : Template.asString(["if (oldTag) {", Template.indent(["oldTag.parentNode.insertBefore(linkTag, oldTag.nextSibling);"]), "} else {", Template.indent(["document.head.appendChild(linkTag);"]), "}"]), "return linkTag;"])};`, `var findStylesheet = ${runtimeTemplate.basicFunction("href, fullhref", ['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 tag;']), "}", '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 tag;"]), "}"])};`, `var loadStylesheet = ${runtimeTemplate.basicFunction("chunkId", `return new Promise(${runtimeTemplate.basicFunction("resolve, reject", [`var href = ${RuntimeGlobals.require}.miniCssF(chunkId);`, `var fullhref = ${RuntimeGlobals.publicPath} + href;`, "if(findStylesheet(href, fullhref)) return resolve();", "createStylesheet(chunkId, fullhref, null, resolve, reject);"])});`)}`, withLoading ? Template.asString(["// object to store loaded CSS chunks", "var installedCssChunks = {", Template.indent( /** @type {string[]} */ chunk.ids.map(id => `${JSON.stringify(id)}: 0`).join(",\n")), "};", "", `${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]) {", 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 ? Template.asString(["var oldTags = [];", "var newTags = [];", `var applyHandler = ${runtimeTemplate.basicFunction("options", [`return { dispose: ${runtimeTemplate.basicFunction("", ["for(var i = 0; i < oldTags.length; i++) {", 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;"])} };`])}`, `${RuntimeGlobals.hmrDownloadUpdateHandlers}.miniCss = ${runtimeTemplate.basicFunction("chunkIds, removedChunks, removedModules, promises, applyHandlers, updatedModulesList", ["applyHandlers.push(applyHandler);", `chunkIds.forEach(${runtimeTemplate.basicFunction("chunkId", [`var href = ${RuntimeGlobals.require}.miniCssF(chunkId);`, `var fullhref = ${RuntimeGlobals.publicPath} + href;`, "var oldTag = findStylesheet(href, fullhref);", "if(!oldTag) return;", `promises.push(new Promise(${runtimeTemplate.basicFunction("resolve, reject", [`var tag = createStylesheet(chunkId, fullhref, oldTag, ${runtimeTemplate.basicFunction("", ['tag.as = "style";', 'tag.rel = "preload";', "resolve();"])}, reject);`, "oldTags.push(oldTag);", "newTags.push(tag);"])}));`])});`])}`]) : "// no hmr"]); } } const enabledChunks = new WeakSet(); /** * @param {Chunk} chunk * @param {Set<string>} set */ const handler = (chunk, set) => { if (enabledChunks.has(chunk)) { return; } enabledChunks.add(chunk); if (typeof this.options.chunkFilename === "string" && /\[(full)?hash(:\d+)?\]/.test(this.options.chunkFilename)) { set.add(RuntimeGlobals.getFullHash); } set.add(RuntimeGlobals.publicPath); compilation.addRuntimeModule(chunk, new runtime.GetChunkFilenameRuntimeModule(MODULE_TYPE, "mini-css", `${RuntimeGlobals.require}.miniCssF`, /** * @param {Chunk} referencedChunk * @returns {TODO} */ referencedChunk => { if (!referencedChunk.contentHash[MODULE_TYPE]) { return false; } return referencedChunk.canBeInitial() ? this.options.filename : this.options.chunkFilename; }, false)); compilation.addRuntimeModule(chunk, new CssLoadingRuntimeModule(set, this.runtimeOptions)); }; compilation.hooks.runtimeRequirementInTree.for(RuntimeGlobals.ensureChunkHandlers).tap(pluginName, handler); compilation.hooks.runtimeRequirementInTree.for(RuntimeGlobals.hmrDownloadUpdateHandlers).tap(pluginName, handler); }); } /** * @private * @param {Chunk} chunk * @param {ChunkGraph} chunkGraph * @returns {Iterable<Module>} */ getChunkModules(chunk, chunkGraph) { return typeof chunkGraph !== "undefined" ? chunkGraph.getOrderedChunkModulesIterable(chunk, compareModulesByIdentifier) : chunk.modulesIterable; } /** * @private * @param {Compilation} compilation * @param {Chunk} chunk * @param {CssModule[]} modules * @param {Compilation["requestShortener"]} requestShortener * @returns {Set<CssModule>} */ sortModules(compilation, chunk, modules, requestShortener) { let usedModules = this._sortedModulesCache.get(chunk); if (usedModules || !modules) { return (/** @type {Set<CssModule>} */usedModules ); } /** @type {CssModule[]} */ const modulesList = [...modules]; // Store dependencies for modules /** @type {Map<CssModule, Set<CssModule>>} */ const moduleDependencies = new Map(modulesList.map(m => [m, /** @type {Set<CssModule>} */ new Set()])); /** @type {Map<CssModule, Map<CssModule, Set<ChunkGroup>>>} */ const moduleDependenciesReasons = new Map(modulesList.map(m => [m, new Map()])); // Get ordered list of modules per chunk group // This loop also gathers dependencies from the ordered lists // Lists are in reverse order to allow to use Array.pop() /** @type {CssModule[][]} */ const modulesByChunkGroup = Array.from(chunk.groupsIterable, chunkGroup => { const sortedModules = modulesList.map(module => { return { module, index: chunkGroup.getModulePostOrderIndex(module) }; }) // eslint-disable-next-line no-undefined .filter(item => item.index !== undefined).sort((a, b) => b.index - a.index).map(item => item.module); for (let i = 0; i < sortedModules.length; i++) { const set = moduleDependencies.get(sortedModules[i]); const reasons = /** @type {Map<CssModule, Set<ChunkGroup>>} */ moduleDependenciesReasons.get(sortedModules[i]); for (let j = i + 1; j < sortedModules.length; j++) { const module = sortedModules[j]; /** @type {Set<CssModule>} */ set.add(module); const reason = reasons.get(module) || /** @type {Set<ChunkGroup>} */new Set(); reason.add(chunkGroup); reasons.set(module, reason); } } return sortedModules; }); // set with already included modules in correct order usedModules = new Set(); /** * @param {CssModule} m * @returns {boolean} */ const unusedModulesFilter = m => ! /** @type {Set<CssModule>} */usedModules.has(m); while (usedModules.size < modulesList.length) { let success = false; let bestMatch; let bestMatchDeps; // get first module where dependencies are fulfilled for (const list of modulesByChunkGroup) { // skip and remove already added modules while (list.length > 0 && usedModules.has(list[list.length - 1])) { list.pop(); } // skip empty lists if (list.length !== 0) { const module = list[list.length - 1]; const deps = moduleDependencies.get(module); // determine dependencies that are not yet included const failedDeps = Array.from( /** @type {Set<CssModule>} */ deps).filter(unusedModulesFilter); // store best match for fallback behavior if (!bestMatchDeps || bestMatchDeps.length > failedDeps.length) { bestMatch = list; bestMatchDeps = failedDeps; } if (failedDeps.length === 0) { // use this module and remove it from list usedModules.add( /** @type {CssModule} */list.pop()); success = true; break; } } } if (!success) { // no module found => there is a conflict // use list with fewest failed deps // and emit a warning const fallbackModule = /** @type {CssModule[]} */bestMatch.pop(); if (!this.options.ignoreOrder) { const reasons = moduleDependenciesReasons.get( /** @type {CssModule} */fallbackModule); compilation.warnings.push( /** @type {WebpackError} */ new Error([`chunk ${chunk.name || chunk.id} [${pluginName}]`, "Conflicting order. Following module has been added:", ` * ${ /** @type {CssModule} */fallbackModule.readableIdentifier(requestShortener)}`, "despite it was not able to fulfill desired ordering with these modules:", ... /** @type {CssModule[]} */bestMatchDeps.map(m => { const goodReasonsMap = moduleDependenciesReasons.get(m); const goodReasons = goodReasonsMap && goodReasonsMap.get( /** @type {CssModule} */fallbackModule); const failedChunkGroups = Array.from( /** @type {Set<ChunkGroup>} */ /** @type {Map<CssModule, Set<ChunkGroup>>} */ reasons.get(m), cg => cg.name).join(", "); const goodChunkGroups = goodReasons && Array.from(goodReasons, cg => cg.name).join(", "); return [` * ${m.readableIdentifier(requestShortener)}`, ` - couldn't fulfill desired order of chunk group(s) ${failedChunkGroups}`, goodChunkGroups && ` - while fulfilling desired order of chunk group(s) ${goodChunkGroups}`].filter(Boolean).join("\n"); })].join("\n"))); } usedModules.add( /** @type {CssModule} */fallbackModule); } } this._sortedModulesCache.set(chunk, usedModules); return usedModules; } /** * @private * @param {Compiler} compiler * @param {Compilation} compilation * @param {Chunk} chunk * @param {CssModule[]} modules * @param {Compiler["requestShortener"]} requestShortener * @param {string} filenameTemplate * @param {Parameters<Exclude<Required<Configuration>['output']['filename'], string | undefined>>[0]} pathData * @returns {Source} */ renderContentAsset(compiler, compilation, chunk, modules, requestShortener, filenameTemplate, pathData) { const usedModules = this.sortModules(compilation, chunk, modules, requestShortener); const { ConcatSource, SourceMapSource, RawSource } = compiler.webpack.sources; const source = new ConcatSource(); const externalsSource = new ConcatSource(); for (const module of usedModules) { let content = module.content.toString(); const readableIdentifier = module.readableIdentifier(requestShortener); const startsWithAtRuleImport = /^@import url/.test(content); let header; if (compilation.outputOptions.pathinfo) { // From https://github.com/webpack/webpack/blob/29eff8a74ecc2f87517b627dee451c2af9ed3f3f/lib/ModuleInfoHeaderPlugin.js#L191-L194 const reqStr = readableIdentifier.replace(/\*\//g, "*_/"); const reqStrStar = "*".repeat(reqStr.length); const headerStr = `/*!****${reqStrStar}****!*\\\n !*** ${reqStr} ***!\n \\****${reqStrStar}****/\n`; header = new RawSource(headerStr); } if (startsWithAtRuleImport) { if (typeof header !== "undefined") { externalsSource.add(header); } // HACK for IE // http://stackoverflow.com/a/14676665/1458162 if (module.media) { // insert media into the @import // this is rar // TODO improve this and parse the CSS to support multiple medias content = content.replace(/;|\s*$/, module.media); } externalsSource.add(content); externalsSource.add("\n"); } else { if (typeof header !== "undefined") { source.add(header); } if (module.supports) { source.add(`@supports (${module.supports}) {\n`); } if (module.media) { source.add(`@media ${module.media} {\n`); } const needLayer = typeof module.layer !== "undefined"; if (needLayer) { source.add(`@layer${module.layer.length > 0 ? ` ${module.layer}` : ""} {\n`); } const { path: filename } = compilation.getPathWithInfo(filenameTemplate, pathData); const undoPath = getUndoPath(filename, compiler.outputPath, false); // replacements content = content.replace(new RegExp(ABSOLUTE_PUBLIC_PATH, "g"), ""); content = content.replace(new RegExp(SINGLE_DOT_PATH_SEGMENT, "g"), "."); content = content.replace(new RegExp(AUTO_PUBLIC_PATH, "g"), undoPath); const entryOptions = chunk.getEntryOptions(); const baseUriReplacement = entryOptions && entryOptions.baseUri || undoPath; content = content.replace(new RegExp(BASE_URI, "g"), baseUriReplacement); if (module.sourceMap) { source.add(new SourceMapSource(content, readableIdentifier, module.sourceMap.toString())); } else { source.add(new RawSource(content)); } source.add("\n"); if (needLayer) { source.add("}\n"); } if (module.media) { source.add("}\n"); } if (module.supports) { source.add("}\n"); } } } return new ConcatSource(externalsSource, source); } } MiniCssExtractPlugin.pluginName = pluginName; MiniCssExtractPlugin.pluginSymbol = pluginSymbol; MiniCssExtractPlugin.loader = require.resolve("./loader"); module.exports = MiniCssExtractPlugin;
SAVE
CANCEL