Eliminate empty js chunks generated by mini-css-extract-plugin when using splitchunks.
To begin, you'll need to install mini-css-extract-optimize-plugin
:
$ npm install mini-css-extract-optimize-plugin --save-dev
Then, all you need to do is adding the mini-css-extract-optimize-plugin
to your webpack
config.
For example:
webpack.config.js
const miniCSSExtractOptimizePlugin = require('mini-css-extract-optimize-plugin');
module.exports = {
plugins: [new miniCSSExtractOptimizePlugin()]
};
To see how i fix this problem step by step, you can refer to this (Written in Chinese).
In webpack 4
with mini-css-extract-plugin
, when you use splitchunks to extract css, it will generate empty JS bundle. This empty JS bundle is useless and will cost us one more network connection.
I want to extract all css files in the directory common/styles
, bundle them into a glabol file base.css
, so all entries could share it without duplicate css code. The webpack config maybe like:
:
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
module: {
rules: [
{
// extract css files in directory `common/styles`
test: /\/common\/styles\/.*css$/ i,
use: [MiniCssExtractPlugin.loader, 'css-loader'],
},
],
},
optimization: {
splitChunks: {
cacheGroups: {
base: {
name: "base",
// bundle css files in directory `common/styles` into one single file
test: /\/common\/styles\/.*(css|scss|sass|less)$/,
chunks: "all",
enforce: true
}
}
}
},
plugins: [new MiniCssExtractPlugin()],
};
It will generate files like:
- base.css
- base.js
Code in base.css
is the style code we need, but code in base.js
shows:
(window["webpackJsonp"] = window["webpackJsonp"] || []).push([["base"],{
/***/ "./src/common/styles/base.scss":
/*!*************************************!*\
!*** ./src/common/styles/base.scss ***!
\*************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
// extracted by mini-css-extract-plugin
/***/ })
}]);
//# sourceMappingURL=base.af983635.js.map
Look, file base.js
is useless and shouldn't be generated at all !!
This problem has been fixed in webpack 5
. But webpack's maintainer don't want to fix it in webpack 4
.
Now you can use this plugin to avoid webpack generating that useless empty chunk.
const miniCSSExtractOptimizePlugin = require('mini-css-extract-optimize-plugin');
module.exports = {
// ... other settings
plugins: [new miniCSSExtractOptimizePlugin()]
};