{"id":13671211,"url":"https://github.com/faceyspacey/extract-css-chunks-webpack-plugin","last_synced_at":"2025-05-14T16:15:14.553Z","repository":{"id":39545983,"uuid":"89552018","full_name":"faceyspacey/extract-css-chunks-webpack-plugin","owner":"faceyspacey","description":"Extract CSS from chunks into multiple stylesheets + HMR","archived":false,"fork":false,"pushed_at":"2024-09-06T10:03:29.000Z","size":3826,"stargazers_count":695,"open_issues_count":21,"forks_count":85,"subscribers_count":13,"default_branch":"master","last_synced_at":"2025-04-30T13:21:26.583Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/faceyspacey.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":".github/CODEOWNERS","security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2017-04-27T03:31:51.000Z","updated_at":"2024-11-07T05:36:22.000Z","dependencies_parsed_at":"2024-10-29T19:04:49.177Z","dependency_job_id":null,"html_url":"https://github.com/faceyspacey/extract-css-chunks-webpack-plugin","commit_stats":{"total_commits":425,"total_committers":89,"mean_commits":4.775280898876405,"dds":0.6799999999999999,"last_synced_commit":"18837c2ddc4175313cfd812698e7fae4ae4a7acc"},"previous_names":[],"tags_count":96,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/faceyspacey%2Fextract-css-chunks-webpack-plugin","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/faceyspacey%2Fextract-css-chunks-webpack-plugin/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/faceyspacey%2Fextract-css-chunks-webpack-plugin/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/faceyspacey%2Fextract-css-chunks-webpack-plugin/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/faceyspacey","download_url":"https://codeload.github.com/faceyspacey/extract-css-chunks-webpack-plugin/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253554071,"owners_count":21926610,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-02T09:01:03.167Z","updated_at":"2025-05-14T16:15:14.534Z","avatar_url":"https://github.com/faceyspacey.png","language":"JavaScript","readme":"If you like our work, check out our Redux-based router \u003ca href=\"https://github.com/faceyspacey/redux-first-router\" target=\"_blank\"\u003eredux-first-router\u003c/a\u003e or its sucessor which, \u003ca href=\"https://github.com/respond-framework/rudy\" target=\"_blank\"\u003eRudy\u003ca\u003e\n\n# extract-css-chunks-webpack-plugin\n\n\u003cp align=\"center\"\u003e\n  \u003ca href=\"https://www.npmjs.com/package/extract-css-chunks-webpack-plugin\"\u003e\n    \u003cimg src=\"https://img.shields.io/npm/v/extract-css-chunks-webpack-plugin.svg\" alt=\"Version\" /\u003e\n  \u003c/a\u003e\n\u003cimg src=\"https://ssl.google-analytics.com/collect?v=1\u0026t=event\u0026ec=email\u0026ea=open\u0026t=event\u0026tid=UA-120967034-1\u0026z=1589684734\u0026cid=9befe819-70e1-278b-50fc-859e6d1970cb\u0026dt=ExtractCssChunks\u0026dp=/email/ExtractCssChunks\"\u003e\n  \u003ca href=\"https://travis-ci.org/faceyspacey/extract-css-chunks-webpack-plugin\"\u003e\n    \u003cimg src=\"https://travis-ci.org/faceyspacey/extract-css-chunks-webpack-plugin.svg?branch=master\" alt=\"Build Status\" /\u003e\n  \u003c/a\u003e\n\n  \u003ca href=\"https://www.npmjs.com/package/extract-css-chunks-webpack-plugin\"\u003e\n    \u003cimg src=\"https://img.shields.io/npm/dt/extract-css-chunks-webpack-plugin.svg\" alt=\"Downloads\" /\u003e\n  \u003c/a\u003e\n\n  \u003ca href=\"https://www.npmjs.com/package/extract-css-chunks-webpack-plugin\"\u003e\n    \u003cimg src=\"https://img.shields.io/npm/dm/extract-css-chunks-webpack-plugin.svg\" alt=\"License\" /\u003e\n  \u003c/a\u003e\n  \n  \u003ca href=\"https://www.npmjs.com/package/extract-css-chunks-webpack-plugin\"\u003e\n    \u003cimg src=\"https://img.shields.io/npm/l/extract-css-chunks-webpack-plugin.svg\" alt=\"License\" /\u003e\n  \u003c/a\u003e\n\u003c/p\u003e\n\n\u003ch2 align=\"center\"\u003e🍾🍾🍾It's our absolute pleasure to announce Webpack 4 Support 🚀🚀🚀\u003c/h2\u003e\n\n\u003e **HEADLINES (May 2018): Now Independently supports Webpack 4:**\n\u003e Yep that's right. The universal family is now fully Webpack 4. Thank you to all our users for your loyalty and patience! If you love Universal, then you are gonna fall head over heels when we bring out the main course!\n\nSo... why did we rebuild `extract-css-chunks-webpack-plugin`? What does it offer?\n\nIt's got all the goodness of `mini-css-extract-plugin` but with 2 gleaming, sought after benefits.\n\nCompared to the existing loaders, we are offering a single solution as opposed to needing to depend on multiple loaders to cater for different features:\n\n## Perks\n\n- **HMR:** It also has first-class support for **Hot Module Replacement** across ALL those css files/chunks!!!\n- cacheable stylesheets\n- smallest total bytes sent compared to \"render-path\" css-in-js solutions that include your CSS definitions in JS\n- Faster than the V2!\n- Async loading\n- No duplicate compilation (performance)\n- Easier to use\n- Specific to CSS\n- SSR Friendly development build, focused on frontend DX\n- Works seamlessly with the Universal family\n- Works fantastically as a standalone style loader (You can use it for any webpack project! with no extra dependencies!)\n- Async styles do not render block webkit browsers, if you use the `insert` option\n\nAdditionally, if you are already a user of the universal family -- we will be waving goodbye to the mandatory `window.__CSS_CHUNKS__`.\n\nThe functionality is still available to you via chunk flushing, and it can come in super handy when needing to easily resolve style assets as urls that might need to be passed to a third party.\n\n**webpack.config.js**\n\n```js\nconst ExtractCssChunks = require('extract-css-chunks-webpack-plugin');\n\nmodule.exports = {\n  plugins: [new ExtractCssChunks()],\n  module: {\n    rules: [\n      {\n        test: /\\.css$/i,\n        use: [ExtractCssChunks.loader, 'css-loader'],\n      },\n    ],\n  },\n};\n```\n\n## Options\n\n### `publicPath`\n\nType: `String|Function`\nDefault: the `publicPath` in `webpackOptions.output`\n\nSpecifies a custom public path for the target file(s).\n\n#### `String`\n\n**webpack.config.js**\n\n```js\nconst ExtractCssChunks = require('extract-css-chunks-webpack-plugin');\n\nmodule.exports = {\n  plugins: [\n    new ExtractCssChunks({\n      // Options similar to the same options in webpackOptions.output\n      // both options are optional\n      filename: '[name].css',\n      chunkFilename: '[id].css',\n    }),\n  ],\n  module: {\n    rules: [\n      {\n        test: /\\.css$/,\n        use: [\n          {\n            loader: ExtractCssChunks.loader,\n            options: {\n              publicPath: '/public/path/to/',\n            },\n          },\n          'css-loader',\n        ],\n      },\n    ],\n  },\n};\n```\n\n#### `Function`\n\n**webpack.config.js**\n\n```js\nconst ExtractCssChunks = require('extract-css-chunks-webpack-plugin');\n\nmodule.exports = {\n  plugins: [\n    new ExtractCssChunks({\n      // Options similar to the same options in webpackOptions.output\n      // both options are optional\n      filename: '[name].css',\n      chunkFilename: '[id].css',\n    }),\n  ],\n  module: {\n    rules: [\n      {\n        test: /\\.css$/,\n        use: [\n          {\n            loader: ExtractCssChunks.loader,\n            options: {\n              publicPath: (resourcePath, context) =\u003e {\n                return path.relative(path.dirname(resourcePath), context) + '/';\n              },\n            },\n          },\n          'css-loader',\n        ],\n      },\n    ],\n  },\n};\n```\n\n### `esModule`\n\nType: `Boolean`\nDefault: `false`\n\nBy default, `extract-css-chunks-webpack-plugin` generates JS modules that use the CommonJS modules syntax.\nThere 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/).\n\nYou can enable a ES module syntax using:\n\n**webpack.config.js**\n\n```js\nconst ExtractCssChunks = require('extract-css-chunks-webpack-plugin');\n\nmodule.exports = {\n  plugins: [new ExtractCssChunks()],\n  module: {\n    rules: [\n      {\n        test: /\\.css$/i,\n        use: [\n          {\n            loader: ExtractCssChunks.loader,\n            options: {\n              esModule: true,\n            },\n          },\n          'css-loader',\n        ],\n      },\n    ],\n  },\n};\n```\n\n## Examples\n\n### Minimal example\n\n**webpack.config.js**\n\n```js\nconst ExtractCssChunks = require('extract-css-chunks-webpack-plugin');\n\nmodule.exports = {\n  plugins: [\n    new ExtractCssChunks({\n      // Options similar to the same options in webpackOptions.output\n      // all options are optional\n      filename: '[name].css',\n      chunkFilename: '[id].css',\n      ignoreOrder: false, // Enable to remove warnings about conflicting order\n    }),\n  ],\n  module: {\n    rules: [\n      {\n        test: /\\.css$/,\n        use: [\n          {\n            loader: ExtractCssChunks.loader,\n            options: {\n              // you can specify a publicPath here\n              // by default it uses publicPath in webpackOptions.output\n              publicPath: '../',\n              hmr: process.env.NODE_ENV === 'development',\n            },\n          },\n          'css-loader',\n        ],\n      },\n    ],\n  },\n};\n```\n\n### The `publicPath` option as function\n\n**webpack.config.js**\n\n```js\nconst ExtractCssChunks = require('extract-css-chunks-webpack-plugin');\n\nmodule.exports = {\n  plugins: [\n    new ExtractCssChunks({\n      // Options similar to the same options in webpackOptions.output\n      // both options are optional\n      filename: '[name].css',\n      chunkFilename: '[id].css',\n    }),\n  ],\n  module: {\n    rules: [\n      {\n        test: /\\.css$/,\n        use: [\n          {\n            loader: ExtractCssChunks.loader,\n            options: {\n              publicPath: (resourcePath, context) =\u003e {\n                // publicPath is the relative path of the resource to the context\n                // e.g. for ./css/admin/main.css the publicPath will be ../../\n                // while for ./css/main.css the publicPath will be ../\n                return path.relative(path.dirname(resourcePath), context) + '/';\n              },\n            },\n          },\n          'css-loader',\n        ],\n      },\n    ],\n  },\n};\n```\n\n### Advanced configuration example\n\nThis plugin should be used only on `production` builds without `style-loader` in the loaders chain, especially if you want to have HMR in `development`.\n\nHere is an example to have both HMR in `development` and your styles extracted in a file for `production` builds.\n\n(Loaders options left out for clarity, adapt accordingly to your needs.)\n\n**webpack.config.js**\n\n```js\nconst ExtractCssChunks = require('extract-css-chunks-webpack-plugin');\nconst devMode = process.env.NODE_ENV !== 'production';\n\nmodule.exports = {\n  plugins: [\n    new ExtractCssChunks({\n      // Options similar to the same options in webpackOptions.output\n      // both options are optional\n      filename: devMode ? '[name].css' : '[name].[hash].css',\n      chunkFilename: devMode ? '[id].css' : '[id].[hash].css',\n    }),\n  ],\n  module: {\n    rules: [\n      {\n        test: /\\.(sa|sc|c)ss$/,\n        use: [\n          {\n            loader: ExtractCssChunks.loader,\n            options: {\n              hmr: process.env.NODE_ENV === 'development',\n            },\n          },\n          'css-loader',\n          'postcss-loader',\n          'sass-loader',\n        ],\n      },\n    ],\n  },\n};\n```\n\n### Hot Module Reloading (HMR)\n\nThe `extract-css-chunks-webpack-plugin` supports hot reloading of actual css files in development.\nSome options are provided to enable HMR of both standard stylesheets and locally scoped CSS or CSS modules.\nBelow is an example configuration of `extract-css-chunks` for HMR use with CSS modules.\n\nWhile we attempt to hmr css-modules. It is not easy to perform when code-splitting with custom chunk names.\n`reloadAll` is an option that should only be enabled if HMR isn't working correctly.\nThe core challenge with css-modules is that when code-split, the chunk ids can and do end up different compared to the filename.\n\n**webpack.config.js**\n\n```js\nconst ExtractCssChunks = require('extract-css-chunks-webpack-plugin');\n\nmodule.exports = {\n  plugins: [\n    new ExtractCssChunks({\n      // Options similar to the same options in webpackOptions.output\n      // both options are optional\n      filename: '[name].css',\n      chunkFilename: '[id].css',\n    }),\n  ],\n  module: {\n    rules: [\n      {\n        test: /\\.css$/,\n        use: [\n          {\n            loader: ExtractCssChunks.loader,\n            options: {\n              // only enable hot in development\n              hmr: process.env.NODE_ENV === 'development',\n              // if hmr does not work, this is a forceful method.\n              reloadAll: true,\n            },\n          },\n          'css-loader',\n        ],\n      },\n    ],\n  },\n};\n```\n\n### Minimizing For Production\n\nTo minify the output, use a plugin like [optimize-css-assets-webpack-plugin](https://github.com/NMFR/optimize-css-assets-webpack-plugin).\nSetting `optimization.minimizer` overrides the defaults provided by webpack, so make sure to also specify a JS minimizer:\n\n**webpack.config.js**\n\n```js\nconst TerserJSPlugin = require('terser-webpack-plugin');\nconst ExtractCssChunks = require('extract-css-chunks-webpack-plugin');\nconst OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');\n\nmodule.exports = {\n  optimization: {\n    minimizer: [new TerserJSPlugin({}), new OptimizeCSSAssetsPlugin({})],\n  },\n  plugins: [\n    new ExtractCssChunks({\n      filename: '[name].css',\n      chunkFilename: '[id].css',\n    }),\n  ],\n  module: {\n    rules: [\n      {\n        test: /\\.css$/,\n        use: [ExtractCssChunks.loader, 'css-loader'],\n      },\n    ],\n  },\n};\n```\n\n### Using preloaded or inlined CSS\n\nThe runtime code detects already added CSS via `\u003clink\u003e` or `\u003cstyle\u003e` tag.\nThis can be useful when injecting CSS on server-side for Server-Side-Rendering.\nThe `href` of the `\u003clink\u003e` tag has to match the URL that will be used for loading the CSS chunk.\nThe `data-href` attribute can be used for `\u003clink\u003e` and `\u003cstyle\u003e` too.\nWhen inlining CSS `data-href` must be used.\n\n### Extracting all CSS in a single file\n\nSimilar to what [extract-text-webpack-plugin](https://github.com/webpack-contrib/extract-text-webpack-plugin) does, the CSS can be extracted in one CSS file using `optimization.splitChunks.cacheGroups`.\n\n**webpack.config.js**\n\n```js\nconst ExtractCssChunks = require('extract-css-chunks-webpack-plugin');\n\nmodule.exports = {\n  optimization: {\n    splitChunks: {\n      cacheGroups: {\n        styles: {\n          name: 'styles',\n          test: /\\.css$/,\n          chunks: 'all',\n          enforce: true,\n        },\n      },\n    },\n  },\n  plugins: [\n    new ExtractCssChunks({\n      filename: '[name].css',\n    }),\n  ],\n  module: {\n    rules: [\n      {\n        test: /\\.css$/,\n        use: [ExtractCssChunks.loader, 'css-loader'],\n      },\n    ],\n  },\n};\n```\n\n### Extracting CSS based on entry\n\nYou may also extract the CSS based on the webpack entry name.\nThis is especially useful if you import routes dynamically but want to keep your CSS bundled according to entry.\nThis also prevents the CSS duplication issue one had with the ExtractTextPlugin.\n\n```js\nconst path = require('path');\nconst ExtractCssChunks = require('extract-css-chunks-webpack-plugin');\n\nfunction recursiveIssuer(m) {\n  if (m.issuer) {\n    return recursiveIssuer(m.issuer);\n  } else if (m.name) {\n    return m.name;\n  } else {\n    return false;\n  }\n}\n\nmodule.exports = {\n  entry: {\n    foo: path.resolve(__dirname, 'src/foo'),\n    bar: path.resolve(__dirname, 'src/bar'),\n  },\n  optimization: {\n    splitChunks: {\n      cacheGroups: {\n        fooStyles: {\n          name: 'foo',\n          test: (m, c, entry = 'foo') =\u003e\n            m.constructor.name === 'CssModule' \u0026\u0026 recursiveIssuer(m) === entry,\n          chunks: 'all',\n          enforce: true,\n        },\n        barStyles: {\n          name: 'bar',\n          test: (m, c, entry = 'bar') =\u003e\n            m.constructor.name === 'CssModule' \u0026\u0026 recursiveIssuer(m) === entry,\n          chunks: 'all',\n          enforce: true,\n        },\n      },\n    },\n  },\n  plugins: [\n    new ExtractCssChunks({\n      filename: '[name].css',\n    }),\n  ],\n  module: {\n    rules: [\n      {\n        test: /\\.css$/,\n        use: [ExtractCssChunks.loader, 'css-loader'],\n      },\n    ],\n  },\n};\n```\n\n### Module Filename Option\n\nWith the `moduleFilename` option you can use chunk data to customize the filename. This is particularly useful when dealing with multiple entry points and wanting to get more control out of the filename for a given entry point/chunk. In the example below, we'll use `moduleFilename` to output the generated css into a different directory.\n\n**webpack.config.js**\n\n```js\nconst ExtractCssChunks = require('extract-css-chunks-webpack-plugin');\n\nmodule.exports = {\n  plugins: [\n    new ExtractCssChunks({\n      moduleFilename: ({ name }) =\u003e `${name.replace('/js/', '/css/')}.css`,\n    }),\n  ],\n  module: {\n    rules: [\n      {\n        test: /\\.css$/,\n        use: [ExtractCssChunks.loader, 'css-loader'],\n      },\n    ],\n  },\n};\n```\n\n### Long Term Caching\n\nFor long term caching use `filename: \"[contenthash].css\"`. Optionally add `[name]`.\n\n**webpack.config.js**\n\n```js\nconst ExtractCssChunks = require('extract-css-chunks-webpack-plugin');\n\nmodule.exports = {\n  plugins: [\n    new ExtractCssChunks({\n      filename: '[name].[contenthash].css',\n      chunkFilename: '[id].[contenthash].css',\n    }),\n  ],\n  module: {\n    rules: [\n      {\n        test: /\\.css$/,\n        use: [ExtractCssChunks.loader, 'css-loader'],\n      },\n    ],\n  },\n};\n```\n\n### Remove Order Warnings\n\nFor projects where css ordering has been mitigated through consistent use of scoping or naming conventions, the css order warnings can be disabled by setting the ignoreOrder flag to true for the plugin.\n\n**webpack.config.js**\n\n```js\nconst ExtractCssChunks = require('extract-css-chunks-webpack-plugin');\n\nmodule.exports = {\n  plugins: [\n    new ExtractCssChunks({\n      ignoreOrder: true,\n    }),\n  ],\n  module: {\n    rules: [\n      {\n        test: /\\.css$/i,\n        use: [ExtractCssChunks.loader, 'css-loader'],\n      },\n    ],\n  },\n};\n```\n\n### insert\n\nType: `Function`\nDefault: `head`\n\nBy default, the `extract-css-chunks-plugin` appends styles (`\u003clink\u003e` elements) to `document.head` of the current `window`.\n\nHowever in some circumstances it might be necessary to have finer control over the append target or even delay `link` elements instertion. For example this is the case when you asynchronously load styles for an application that runs inside of an iframe. In such cases `insert` can be configured to be a function or a custom selector.\n\nIf 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.\n\n#### `insert` as a function\n\nAllows to override default behavior and insert styles at any position.\n\n\u003e ⚠ 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.\n\n\u003e ⚠ 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.\n\n```js\nnew ExtractCssChunksPlugin({\n  insert: function insert(linkTag) {\n    const reference = document.querySelector('#some-element');\n    if (reference) {\n      reference.parentNode.insertBefore(linkTag, reference);\n    }\n  },\n});\n```\n\nA new `\u003clink\u003e` element will be inserted before the element with id `some-element`.\n\n### Media Query Plugin\n\nIf 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:\n\n- [Media Query Plugin](https://github.com/SassNinja/media-query-plugin)\n- [Media Query Splitting Plugin](https://github.com/mike-diamond/media-query-splitting-plugin)\n","funding_links":[],"categories":["JavaScript"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffaceyspacey%2Fextract-css-chunks-webpack-plugin","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffaceyspacey%2Fextract-css-chunks-webpack-plugin","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffaceyspacey%2Fextract-css-chunks-webpack-plugin/lists"}