This time I will show you how to implement webpack4 css packaging and compression, and what are the precautions to implement webpack4 css packaging and compression. The following is a practical case, let's take a look.
// webpack.config.js
module.exports = {
// webpack会根据mode进行对Js打包,development压缩,production下面自动压缩,亲测没有问题
mode: 'development' // production
}
Copy after login
But how to package the css separated from js?
I have been looking for relevant articles for a day. Many of them say that webpack automatically supports CSS compression, and some say that a plug-in is required. Yes, that is, use a plug-in.
optimize-css-assets-webpack-plugin
But be sure to read the Npm official website
⚠️ For webpack v3 or below please use optimize-css-assets-webpack-plugin@3.2.0. The optimize-css-assets-webpack-plugin@4.0. 0 version and above supports webpack v4.
The method is to
install it first optimize-css-assets-webpack-plugin
const optimizeCss = require('optimize-css-assets-webpack-plugin');
module.exports = {
.....,
//
plugins: [
new optimizeCss({
assetNameRegExp: /\.style\.css$/g,
cssProcessor: require('cssnano'),
cssProcessorOptions: { discardComments: { removeAll: true } },
canPrint: true
}),
],
// 这个还待研究,看字面意思是优化的意思
optimization: {
// minimize: true,
minimizer: [new optimizeCss({})],
}
}
Copy after login
I also read the above code written by others , so you need to install a 'cssnano' package
and then run the production environment packaging command. Oh, the css is indeed compressed, but looking at the js, it is not compressed. If the above code is not added, js is indeed the default Compressed, so I looked for a solution on the Internet. They said that webpack4 only needs to set the mode production, but now there is a problem. After compressing the css, the js will not be compressed, so I continued to install the previous plug-in for compressing Js with the intention of giving it a try. uglify-webpack-plugin
Finally, I found that the problem was solved. It’s just my experience and it was a mistake. But if you have a good solution, please leave a message and make progress together to understand webpack thoroughly!
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
Detailed explanation of using Node.js Buffer
How to use JS to call the local camera
The above is the detailed content of How to implement webpack4 css packaging and compression. For more information, please follow other related articles on the PHP Chinese website!