Gathering detailed insights and metrics for mini-css-extract-plugin
NPM was acquired by GitHub in March 2020.
Gathering detailed insights and metrics for mini-css-extract-plugin
NPM was acquired by GitHub in March 2020.
npm install mini-css-extract-plugin
58.4
Supply Chain
71.6
Quality
87.3
Maintenance
100
Vulnerability
4,659 Stars
450 Commits
388 Forks
78 Watching
7 Branches
90 Contributors
Updated on 13 Nov 2024
Minified
Minified + Gzipped
JavaScript (93.68%)
CSS (5.51%)
HTML (0.75%)
Shell (0.03%)
SCSS (0.03%)
Cumulative downloads
Total Downloads
Last day
2.1%
2,512,837
Compared to previous day
Last week
11.3%
13,291,678
Compared to previous week
Last month
10.4%
55,771,801
Compared to previous month
Last year
-2.2%
637,849,160
Compared to previous year
2
1
35
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:
To begin, you'll need to install mini-css-extract-plugin
:
1npm install --save-dev mini-css-extract-plugin
or
1yarn add -D mini-css-extract-plugin
or
1pnpm add -D mini-css-extract-plugin
It's recommended to combine mini-css-extract-plugin
with the css-loader
Then add the loader and the plugin to your webpack
config. For example:
style.css
1body { 2 background: green; 3}
component.js
1import "./style.css";
webpack.config.js
1const MiniCssExtractPlugin = require("mini-css-extract-plugin"); 2 3module.exports = { 4 plugins: [new MiniCssExtractPlugin()], 5 module: { 6 rules: [ 7 { 8 test: /\.css$/i, 9 use: [MiniCssExtractPlugin.loader, "css-loader"], 10 }, 11 ], 12 }, 13};
[!WARNING]
Note that if you import CSS from your webpack entrypoint or import styles in the initial chunk,
mini-css-extract-plugin
will not load this CSS into the page. Please usehtml-webpack-plugin
for automatic generationlink
tags or createindex.html
file withlink
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 thesourceMappingURL
comment (i.e.//# sourceMappingURL=style.css.map
). If you need setdevtool
to another value you can enable source maps generation for extracted CSS usingsourceMap: true
forcss-loader
.
filename
Type:
1type filename = 2 | string 3 | ((pathData: PathData, assetInfo?: AssetInfo) => string);
Default: [name].css
This option determines the name of each output CSS file.
Works like output.filename
chunkFilename
Type:
1type chunkFilename = 2 | string 3 | ((pathData: PathData, assetInfo?: AssetInfo) => string);
Default: based on filename
Specifying
chunkFilename
as afunction
is only available in webpack@5
This option determines the name of non-entry chunk files.
Works like output.chunkFilename
ignoreOrder
Type:
1type ignoreOrder = boolean;
Default: false
Remove Order Warnings. See examples below for details.
insert
Type:
1type insert = string | ((linkTag: HTMLLinkElement) => void);
Default: document.head.appendChild(linkTag);
Inserts the link
tag at the given position for non-initial (async) CSS chunks
[!WARNING]
Only for non-initial (async) 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 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.
A new <link>
element will be inserted after the found item.
webpack.config.js
1new MiniCssExtractPlugin({
2 insert: "#some-element",
3});
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
1new MiniCssExtractPlugin({
2 insert: function (linkTag) {
3 var reference = document.querySelector("#some-element");
4 if (reference) {
5 reference.parentNode.insertBefore(linkTag, reference);
6 }
7 },
8});
A new <link>
element will be inserted before the element with id some-element
.
attributes
Type:
1type attributes = Record<string, string>};
Default: {}
[!WARNING]
Only for non-initial (async) chunks.
If defined, the mini-css-extract-plugin
will attach given attributes with their values on <link>
element.
webpack.config.js
1const MiniCssExtractPlugin = require("mini-css-extract-plugin"); 2 3module.exports = { 4 plugins: [ 5 new MiniCssExtractPlugin({ 6 attributes: { 7 id: "target", 8 "data-target": "example", 9 }, 10 }), 11 ], 12 module: { 13 rules: [ 14 { 15 test: /\.css$/i, 16 use: [MiniCssExtractPlugin.loader, "css-loader"], 17 }, 18 ], 19 }, 20};
[!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
linkType
Type:
1type 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
1const MiniCssExtractPlugin = require("mini-css-extract-plugin"); 2 3module.exports = { 4 plugins: [ 5 new MiniCssExtractPlugin({ 6 linkType: "text/css", 7 }), 8 ], 9 module: { 10 rules: [ 11 { 12 test: /\.css$/i, 13 use: [MiniCssExtractPlugin.loader, "css-loader"], 14 }, 15 ], 16 }, 17};
boolean
false
disables the link type
attribute
webpack.config.js
1const MiniCssExtractPlugin = require("mini-css-extract-plugin"); 2 3module.exports = { 4 plugins: [ 5 new MiniCssExtractPlugin({ 6 linkType: false, 7 }), 8 ], 9 module: { 10 rules: [ 11 { 12 test: /\.css$/i, 13 use: [MiniCssExtractPlugin.loader, "css-loader"], 14 }, 15 ], 16 }, 17};
runtime
Type:
1type 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 to retrieve them then use your own runtime code to download assets when needed.
false
to skip.
webpack.config.js
1const MiniCssExtractPlugin = require("mini-css-extract-plugin"); 2 3module.exports = { 4 plugins: [ 5 new MiniCssExtractPlugin({ 6 runtime: false, 7 }), 8 ], 9 module: { 10 rules: [ 11 { 12 test: /\.css$/i, 13 use: [MiniCssExtractPlugin.loader, "css-loader"], 14 }, 15 ], 16 }, 17};
experimentalUseImportModule
Type:
1type 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
1const MiniCssExtractPlugin = require("mini-css-extract-plugin"); 2 3module.exports = { 4 plugins: [ 5 new MiniCssExtractPlugin({ 6 // You don't need this for `>= 5.52.0` due to the fact that this is enabled by default 7 // Required only for `>= 5.33.2 & <= 5.52.0` 8 // Not available/unsafe for `<= 5.33.2` 9 experimentalUseImportModule: true, 10 }), 11 ], 12 module: { 13 rules: [ 14 { 15 test: /\.css$/i, 16 use: [MiniCssExtractPlugin.loader, "css-loader"], 17 }, 18 ], 19 }, 20};
publicPath
Type:
1type publicPath = 2 | string 3 | ((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
string
webpack.config.js
1const MiniCssExtractPlugin = require("mini-css-extract-plugin"); 2 3module.exports = { 4 plugins: [ 5 new MiniCssExtractPlugin({ 6 // Options similar to the same options in webpackOptions.output 7 // both options are optional 8 filename: "[name].css", 9 chunkFilename: "[id].css", 10 }), 11 ], 12 module: { 13 rules: [ 14 { 15 test: /\.css$/, 16 use: [ 17 { 18 loader: MiniCssExtractPlugin.loader, 19 options: { 20 publicPath: "/public/path/to/", 21 }, 22 }, 23 "css-loader", 24 ], 25 }, 26 ], 27 }, 28};
function
webpack.config.js
1const MiniCssExtractPlugin = require("mini-css-extract-plugin"); 2 3module.exports = { 4 plugins: [ 5 new MiniCssExtractPlugin({ 6 // Options similar to the same options in webpackOptions.output 7 // both options are optional 8 filename: "[name].css", 9 chunkFilename: "[id].css", 10 }), 11 ], 12 module: { 13 rules: [ 14 { 15 test: /\.css$/, 16 use: [ 17 { 18 loader: MiniCssExtractPlugin.loader, 19 options: { 20 publicPath: (resourcePath, context) => { 21 return path.relative(path.dirname(resourcePath), context) + "/"; 22 }, 23 }, 24 }, 25 "css-loader", 26 ], 27 }, 28 ], 29 }, 30};
emit
Type:
1type 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:
1type 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 and tree shaking.
You can enable a CommonJS syntax using:
webpack.config.js
1const MiniCssExtractPlugin = require("mini-css-extract-plugin"); 2 3module.exports = { 4 plugins: [new MiniCssExtractPlugin()], 5 module: { 6 rules: [ 7 { 8 test: /\.css$/i, 9 use: [ 10 { 11 loader: MiniCssExtractPlugin.loader, 12 options: { 13 esModule: false, 14 }, 15 }, 16 "css-loader", 17 ], 18 }, 19 ], 20 }, 21};
defaultExport
Type:
1type defaultExport = boolean;
Default: false
[!NOTE]
This option will work only when you set
namedExport
totrue
incss-loader
By default, mini-css-extract-plugin
generates JS modules based on the esModule
and namedExport
options in css-loader
.
Using the esModule
and namedExport
options will allow you to better optimize your code.
If you set esModule: true
and namedExport: true
for css-loader
mini-css-extract-plugin
will generate only a named export.
Our official recommendation is to use only named export for better future compatibility.
But for some applications, it is not easy to quickly rewrite the code from the default export to a named export.
In case you need both default and named exports, you can enable this option:
webpack.config.js
1const MiniCssExtractPlugin = require("mini-css-extract-plugin"); 2 3module.exports = { 4 plugins: [new MiniCssExtractPlugin()], 5 module: { 6 rules: [ 7 { 8 test: /\.css$/i, 9 use: [ 10 { 11 loader: MiniCssExtractPlugin.loader, 12 options: { 13 defaultExport: true, 14 }, 15 }, 16 { 17 loader: "css-loader", 18 options: { 19 esModule: true, 20 modules: { 21 namedExport: true, 22 }, 23 }, 24 }, 25 ], 26 }, 27 ], 28 }, 29};
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, because it injects CSS into the DOM using multiple and works faster.
Do not use
style-loader
andmini-css-extract-plugin
together.
webpack.config.js
1const MiniCssExtractPlugin = require("mini-css-extract-plugin"); 2const devMode = process.env.NODE_ENV !== "production"; 3 4module.exports = { 5 module: { 6 rules: [ 7 { 8 // If you enable `experiments.css` or `experiments.futureDefaults`, please uncomment line below 9 // type: "javascript/auto", 10 test: /\.(sa|sc|c)ss$/, 11 use: [ 12 devMode ? "style-loader" : MiniCssExtractPlugin.loader, 13 "css-loader", 14 "postcss-loader", 15 "sass-loader", 16 ], 17 }, 18 ], 19 }, 20 plugins: [].concat(devMode ? [] : [new MiniCssExtractPlugin()]), 21};
webpack.config.js
1const MiniCssExtractPlugin = require("mini-css-extract-plugin"); 2 3module.exports = { 4 plugins: [ 5 new MiniCssExtractPlugin({ 6 // Options similar to the same options in webpackOptions.output 7 // all options are optional 8 filename: "[name].css", 9 chunkFilename: "[id].css", 10 ignoreOrder: false, // Enable to remove warnings about conflicting order 11 }), 12 ], 13 module: { 14 rules: [ 15 { 16 test: /\.css$/, 17 use: [ 18 { 19 loader: MiniCssExtractPlugin.loader, 20 options: { 21 // you can specify a publicPath here 22 // by default it uses publicPath in webpackOptions.output 23 publicPath: "../", 24 }, 25 }, 26 "css-loader", 27 ], 28 }, 29 ], 30 }, 31};
âš Names of locals are converted to
camelCase
.
âš It is not allowed to use JavaScript reserved words in css class names.
âš Options
esModule
andmodules.namedExport
incss-loader
should be enabled.
styles.css
1.foo-baz { 2 color: red; 3} 4.bar { 5 color: blue; 6}
index.js
1import { fooBaz, bar } from "./styles.css"; 2 3console.log(fooBaz, bar);
You can enable a ES module named export using:
webpack.config.js
1const MiniCssExtractPlugin = require("mini-css-extract-plugin"); 2 3module.exports = { 4 plugins: [new MiniCssExtractPlugin()], 5 module: { 6 rules: [ 7 { 8 test: /\.css$/, 9 use: [ 10 { 11 loader: MiniCssExtractPlugin.loader, 12 }, 13 { 14 loader: "css-loader", 15 options: { 16 esModule: true, 17 modules: { 18 namedExport: true, 19 localIdentName: "foo__[name]__[local]", 20 }, 21 }, 22 }, 23 ], 24 }, 25 ], 26 }, 27};
publicPath
option as functionwebpack.config.js
1const MiniCssExtractPlugin = require("mini-css-extract-plugin"); 2 3module.exports = { 4 plugins: [ 5 new MiniCssExtractPlugin({ 6 // Options similar to the same options in webpackOptions.output 7 // both options are optional 8 filename: "[name].css", 9 chunkFilename: "[id].css", 10 }), 11 ], 12 module: { 13 rules: [ 14 { 15 test: /\.css$/, 16 use: [ 17 { 18 loader: MiniCssExtractPlugin.loader, 19 options: { 20 publicPath: (resourcePath, context) => { 21 // publicPath is the relative path of the resource to the context 22 // e.g. for ./css/admin/main.css the publicPath will be ../../ 23 // while for ./css/main.css the publicPath will be ../ 24 return path.relative(path.dirname(resourcePath), context) + "/"; 25 }, 26 }, 27 }, 28 "css-loader", 29 ], 30 }, 31 ], 32 }, 33};
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
1const webpack = require("webpack"); 2const MiniCssExtractPlugin = require("mini-css-extract-plugin"); 3const devMode = process.env.NODE_ENV !== "production"; 4 5const plugins = [ 6 new MiniCssExtractPlugin({ 7 // Options similar to the same options in webpackOptions.output 8 // both options are optional 9 filename: devMode ? "[name].css" : "[name].[contenthash].css", 10 chunkFilename: devMode ? "[id].css" : "[id].[contenthash].css", 11 }), 12]; 13if (devMode) { 14 // only enable hot in development 15 plugins.push(new webpack.HotModuleReplacementPlugin()); 16} 17 18module.exports = { 19 plugins, 20 module: { 21 rules: [ 22 { 23 test: /\.(sa|sc|c)ss$/, 24 use: [ 25 MiniCssExtractPlugin.loader, 26 "css-loader", 27 "postcss-loader", 28 "sass-loader", 29 ], 30 }, 31 ], 32 }, 33};
[!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
1const webpack = require("webpack"); 2const MiniCssExtractPlugin = require("mini-css-extract-plugin"); 3 4const plugins = [ 5 new MiniCssExtractPlugin({ 6 // Options similar to the same options in webpackOptions.output 7 // both options are optional 8 filename: devMode ? "[name].css" : "[name].[contenthash].css", 9 chunkFilename: devMode ? "[id].css" : "[id].[contenthash].css", 10 }), 11]; 12if (devMode) { 13 // only enable hot in development 14 plugins.push(new webpack.HotModuleReplacementPlugin()); 15} 16 17module.exports = { 18 plugins, 19 module: { 20 rules: [ 21 { 22 test: /\.css$/, 23 use: [ 24 { 25 loader: MiniCssExtractPlugin.loader, 26 options: {}, 27 }, 28 "css-loader", 29 ], 30 }, 31 ], 32 }, 33};
To minify the output, use a plugin like css-minimizer-webpack-plugin.
webpack.config.js
1const MiniCssExtractPlugin = require("mini-css-extract-plugin"); 2const CssMinimizerPlugin = require("css-minimizer-webpack-plugin"); 3 4module.exports = { 5 plugins: [ 6 new MiniCssExtractPlugin({ 7 filename: "[name].css", 8 chunkFilename: "[id].css", 9 }), 10 ], 11 module: { 12 rules: [ 13 { 14 test: /\.css$/, 15 use: [MiniCssExtractPlugin.loader, "css-loader"], 16 }, 17 ], 18 }, 19 optimization: { 20 minimizer: [ 21 // For webpack@5 you can use the `...` syntax to extend existing minimizers (i.e. `terser-webpack-plugin`), uncomment the next line 22 // `...`, 23 new CssMinimizerPlugin(), 24 ], 25 }, 26};
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.
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.
The CSS can be extracted in one CSS file using optimization.splitChunks.cacheGroups
.
webpack.config.js
1const MiniCssExtractPlugin = require("mini-css-extract-plugin"); 2 3module.exports = { 4 optimization: { 5 splitChunks: { 6 cacheGroups: { 7 styles: { 8 name: "styles", 9 type: "css/mini-extract", 10 chunks: "all", 11 enforce: true, 12 }, 13 }, 14 }, 15 }, 16 plugins: [ 17 new MiniCssExtractPlugin({ 18 filename: "[name].css", 19 }), 20 ], 21 module: { 22 rules: [ 23 { 24 test: /\.css$/, 25 use: [MiniCssExtractPlugin.loader, "css-loader"], 26 }, 27 ], 28 }, 29};
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).
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.
1const path = require("path"); 2const MiniCssExtractPlugin = require("mini-css-extract-plugin"); 3 4module.exports = { 5 entry: { 6 foo: path.resolve(__dirname, "src/foo"), 7 bar: path.resolve(__dirname, "src/bar"), 8 }, 9 optimization: { 10 splitChunks: { 11 cacheGroups: { 12 fooStyles: { 13 type: "css/mini-extract", 14 name: "styles_foo", 15 chunks: (chunk) => { 16 return chunk.name === "foo"; 17 }, 18 enforce: true, 19 }, 20 barStyles: { 21 type: "css/mini-extract", 22 name: "styles_bar", 23 chunks: (chunk) => { 24 return chunk.name === "bar"; 25 }, 26 enforce: true, 27 }, 28 }, 29 }, 30 }, 31 plugins: [ 32 new MiniCssExtractPlugin({ 33 filename: "[name].css", 34 }), 35 ], 36 module: { 37 rules: [ 38 { 39 test: /\.css$/, 40 use: [MiniCssExtractPlugin.loader, "css-loader"], 41 }, 42 ], 43 }, 44};
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
1const MiniCssExtractPlugin = require("mini-css-extract-plugin"); 2 3module.exports = { 4 plugins: [ 5 new MiniCssExtractPlugin({ 6 filename: ({ chunk }) => `${chunk.name.replace("/js/", "/css/")}.css`, 7 }), 8 ], 9 module: { 10 rules: [ 11 { 12 test: /\.css$/, 13 use: [MiniCssExtractPlugin.loader, "css-loader"], 14 }, 15 ], 16 }, 17};
For long term caching use filename: "[contenthash].css"
. Optionally add [name]
.
webpack.config.js
1const MiniCssExtractPlugin = require("mini-css-extract-plugin"); 2 3module.exports = { 4 plugins: [ 5 new MiniCssExtractPlugin({ 6 filename: "[name].[contenthash].css", 7 chunkFilename: "[id].[contenthash].css", 8 }), 9 ], 10 module: { 11 rules: [ 12 { 13 test: /\.css$/, 14 use: [MiniCssExtractPlugin.loader, "css-loader"], 15 }, 16 ], 17 }, 18};
For projects where css ordering has been mitigated through consistent use of scoping or naming conventions, such as CSS Modules, the css order warnings can be disabled by setting the ignoreOrder flag to true for the plugin.
webpack.config.js
1const MiniCssExtractPlugin = require("mini-css-extract-plugin"); 2 3module.exports = { 4 plugins: [ 5 new MiniCssExtractPlugin({ 6 ignoreOrder: true, 7 }), 8 ], 9 module: { 10 rules: [ 11 { 12 test: /\.css$/i, 13 use: [MiniCssExtractPlugin.loader, "css-loader"], 14 }, 15 ], 16 }, 17};
webpack.config.js
1const MiniCssExtractPlugin = require("mini-css-extract-plugin"); 2 3module.exports = { 4 entry: "./src/index.js", 5 module: { 6 rules: [ 7 { 8 test: /\.s[ac]ss$/i, 9 oneOf: [ 10 { 11 resourceQuery: "?dark", 12 use: [ 13 MiniCssExtractPlugin.loader, 14 "css-loader", 15 { 16 loader: "sass-loader", 17 options: { 18 additionalData: `@use 'dark-theme/vars' as vars;`, 19 }, 20 }, 21 ], 22 }, 23 { 24 use: [ 25 MiniCssExtractPlugin.loader, 26 "css-loader", 27 { 28 loader: "sass-loader", 29 options: { 30 additionalData: `@use 'light-theme/vars' as vars;`, 31 }, 32 }, 33 ], 34 }, 35 ], 36 }, 37 ], 38 }, 39 plugins: [ 40 new MiniCssExtractPlugin({ 41 filename: "[name].css", 42 attributes: { 43 id: "theme", 44 }, 45 }), 46 ], 47};
src/index.js
1import "./style.scss"; 2 3let theme = "light"; 4const themes = {}; 5 6themes[theme] = document.querySelector("#theme"); 7 8async function loadTheme(newTheme) { 9 // eslint-disable-next-line no-console 10 console.log(`CHANGE THEME - ${newTheme}`); 11 12 const themeElement = document.querySelector("#theme"); 13 14 if (themeElement) { 15 themeElement.remove(); 16 } 17 18 if (themes[newTheme]) { 19 // eslint-disable-next-line no-console 20 console.log(`THEME ALREADY LOADED - ${newTheme}`); 21 22 document.head.appendChild(themes[newTheme]); 23 24 return; 25 } 26 27 if (newTheme === "dark") { 28 // eslint-disable-next-line no-console 29 console.log(`LOADING THEME - ${newTheme}`); 30 31 import(/* webpackChunkName: "dark" */ "./style.scss?dark").then(() => { 32 themes[newTheme] = document.querySelector("#theme"); 33 34 // eslint-disable-next-line no-console 35 console.log(`LOADED - ${newTheme}`); 36 }); 37 } 38} 39 40document.onclick = () => { 41 if (theme === "light") { 42 theme = "dark"; 43 } else { 44 theme = "light"; 45 } 46 47 loadTheme(theme); 48};
src/dark-theme/_vars.scss
1$background: black;
src/light-theme/_vars.scss
1$background: white;
src/styles.scss
1body { 2 background-color: vars.$background; 3}
public/index.html
1<!DOCTYPE html> 2<html lang="en"> 3 <head> 4 <meta charset="UTF-8" /> 5 <meta name="viewport" content="width=device-width, initial-scale=1" /> 6 <title>Document</title> 7 <link id="theme" rel="stylesheet" type="text/css" href="./main.css" /> 8 </head> 9 <body> 10 <script src="./main.js"></script> 11 </body> 12</html>
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:
The mini-css-extract-plugin provides hooks to extend it to your needs.
SyncWaterfallHook
Called before inject the insert code for link tag. Should return a string
1MiniCssExtractPlugin.getCompilationHooks(compilation).beforeTagInsert.tap( 2 "changeHref", 3 (source, varNames) => 4 Template.asString([ 5 source, 6 `${varNames.tag}.setAttribute("href", "https://github.com/webpack-contrib/mini-css-extract-plugin");`, 7 ]) 8);
Please take a moment to read our contributing guidelines if you haven't yet done so.
No vulnerabilities found.
Reason
4 commit(s) and 8 issue activity found in the last 90 days -- score normalized to 10
Reason
license file detected
Details
Reason
no dangerous workflow patterns detected
Reason
GitHub workflow tokens follow principle of least privilege
Details
Reason
no binaries found in the repo
Reason
Found 12/27 approved changesets -- score normalized to 4
Reason
dependency not pinned by hash detected -- score normalized to 3
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
12 existing vulnerabilities detected
Details
Score
Last Scanned on 2024-11-04
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn Moressr-mini-css-extract-plugin
extracts CSS into separate files
@vusion/mini-css-extract-plugin
extracts CSS into separate files
webpack-remove-empty-scripts
Webpack plugin removes empty JavaScript files generated when using styles.
@prepair/extract-css-chunks-webpack-plugin
Extract CSS from chunks into stylesheets + HMR. Supports Webpack 4 + SSR