This is a series of articles to share the record, this is mainly the basis of webpack CSS \ JS optimization, such as when we are in the production environment, more need to consider the style separation, (because the package is a JS, CSS in the whole JS, so the package will be large), CSS compatibility (postCSS), Some styles in different browsers have compatibility issues to deal with, compress style files, make CSS packages smaller, faster packaging and other operations, remove useless CSS sharing.

Official start:

Prepare the skills

Basic NodeJS knowledge and NPM instructions

“Webpack “: “^5.68.0″,”webpack-cli”: “^4.9.2”

webpack-bundle-analyzer

Package performance analysis plug-in: Webpack-bundle-Analyzer

This plug-in can help us analyze where the WebPack packaging process can be improved.

NPM address: www.npmjs.com/package/web…

use

1, install,

npm install --save-dev webpack-bundle-analyzer
Copy the code

2. Modify the webpack.config.js configuration

First introduced

const {BundleAnalyzerPlugin} = require('webpack-bundle-analyzer');
Copy the code

Configure in plugins:

plugins: [
    new BundleAnalyzerPlugin()
  ]
Copy the code

3. Run WebPack — Progress

Will automatically open the browser localhost:8888, or 127.0.0.1:8888 on this page,

Out of the CSS

Why pull out CSS

The default packaging is, CSS is in JS, so js files are big, and if this is published in production,

Because the style is dynamically inserted into the head when JS is loading, it will cause a flash screen.

The entry file becomes large and the project starts slowly. So we need to extract CSS from JS.

Because CSS downloads and JS can be done in parallel, when an HTML file is large, we can extract the CSS and load it separately, which can solve the problem.

Use ideas:

    • Use the mini-CSs-extract-plugin
    • Download plugin, new plugin, instead of style-loader, use
    • It is recommended that the mini-CSS-extract-plugin be used together with CSS-Loader.

1, install,

npm install  mini-css-extract-plugin --save-dev
Copy the code

2. Modify the webpack.config.js configuration

const MiniCssExtractPlugin = require('mini-css-extract-plugin')
Copy the code

MiniCssExtractPlugin. Replace style – loader loader

Add a new plugin to plugin

new MiniCssExtractPlugin({
                filename: 'css/built.css'
            }),
Copy the code

Complete code:

const { resolve } = require('path'); const { CleanWebpackPlugin } = require('clean-webpack-plugin') const HtmlWebpackPlugin = require('html-webpack-plugin') Const MiniCssExtractPlugin = require('mini-css-extract-plugin') const config = (mode) => {return {// webpack configuration // // Output path __dirName nodejs The variable represents the absolute path of the current file directory path: Resolve (__dirname, 'build'), // output Ming filename: 'build.js'}, // loader configuration module: {rules: [{// match CSS ending file test: /.css$/, // use css-loader to make webpack recognize // single loader using loader attributes //loader: 'css-loader' // Multiple loaders need to use the use attribute in reverse order, i.e. the end of the array -> the beginning of the array use: [MiniCssExtractPlugin. Loader, 'CSS - loader]}, {/ / match to less the test at the end of the file: /.less$/, / / less - loader speak less file into the CSS file (need to download the two rely on less and less - loder) / / CSS - loader in the CSS file into a commonjs module is loaded into the js / / style is the inside content strings // use array to execute in backorder, that is, execute 'style-loader' first, When executing 'csS-loader' when executing 'style-loader' use: [MiniCssExtractPlugin. Loader, 'CSS - loader', 'less - loader]}, {/ / match to SCSS the test at the end of the file: /. SCSS $/, use: [MiniCssExtractPlugin. Loader, 'CSS - loader', 'sass - loader]}, {/ pictures/processing / / the problem: the default is not in the HTML img image test: /.(jpe?g|png|gif|svg)$/, type: "asset/resource", generator: {/ / and the output. AssetModuleFilename is the same, the time of this writing is introduced into will also add the filename path: '[name][ext]'},}, {// handle HTML // error: /.html$/, // To use a loader attribute value as a string, multiple use values as an array // to use the HTML img image (responsible for importing img in the url-loader process) loader: 'html-loader', // htmL-loader can't display images. Turn off es6 module parsing. Use commonJS module parsing. False //}}]}, // plugins: [// function: New HtmlWebpackPlugin({// Copy './index.html') {// Copy './index.html' Template: './index.html'}), new MiniCssExtractPlugin({filename: 'CSS/build.css'}), // Clean build folder new CleanWebpackPlugin()], mode: 'development', // build mode // build mode: 'production', // production mode // devServer for automation (auto compile auto open browser auto refresh browser...) NPX webpack-dev-server = NPX webpack-dev-server = NPX webpack-dev-server DevServer: {// NPX webpack-dev-server: {// NPX webpack-dev-server: {// NPX webpack-dev-server: Resolve (__dirname, 'build'), // enable gzip compress: true, // port: 8888, // automatically open browser: true, // enable HMR function hot: Proxy: {'/ API ': {target: 'http://localhost:5000', pathRewrite: {'/ API ': {target: 'http://localhost:5000', pathRewrite: { '^/api': '' } } } }, } } module.exports = (env, argv) => { console.log('argv.mode=', argv.mode, "env:", Return config(argv.mode); }Copy the code

3. Run WebPack — Progress

We can see that there is a CSS folder in the Build folder and a built-in

The entire CSS is all we’ve introduced using CSS, LESS, and Sass.

The size of the build.js package is also smaller.

Look at the browser, the style is no problem

Package analysis is automatically enabled every time we compile, which is annoying. We can only enable it if we want

New BundleAnalyzerPlugin({analyzerMode: 'disabled', // do not start the HTTP service generateStatsFile: true // to generate stats.json}),Copy the code

Add commands to package.json

​
        "analyzer":"webpack-bundle-analyzer --port 8888 ./build/stats.json"
Copy the code

Run the NPM run Analyzer command

CSS compatibility

  • For browser compatibility, we sometimes have to add prefixes like -webkit,-ms,-o, and -moz

    • Trident kernel: mainly represents Internet Explorer and is prefixed with -ms
    • Gecko kernel: Mainly represents Firefox and is prefixed with -moz
    • Presto kernel: Mainly represents Opera and is prefixed with -o
    • Webkit kernel: Represents Chrome and Safari with the prefix – Webkit
  • Placeholder elements ::placeholder allows you to select placeholder text for a form element, which allows developers and designers to customize the placeholder text style.

So we need Webpack to help us complete the compatibility of CSS, we can use PostCSS to handle CSS, in webpack we use postCSs-loader to handle CSS, postCSs-loader depends on PostCSS, Postcss-preset -env transforms modern CSS into something that most browsers can understand (helps PostCSS recognize the environment and load the appropriate configuration, making the code compatible with every browser version)

Postcss-preset -env: Help PostCSS find the configuration in package.json browserslist and load the specified CSS compatibility style using the configuration

  • The PostCSS Preset Env is already includedautoprefixerandbrowsersoptions

1, install,

npm i postcss-loader postcss  postcss-preset-env --save-dev
Copy the code

2. Create postcss.config.js

Here we will postcss – loader plug-in set out alone on postcss. Config. Js, let postcss – loader configuration more concise. It can also be configured in webpack.config.js.

postcss.config.js

let postcssPresetEnv = require('postcss-preset-env');
module.exports={
    plugins:[postcssPresetEnv({
        browsers: 'last 5 version'
    })]
}
Copy the code

3. Modify package.json

Help PostCSS find the configuration inside package.json browerslist and load the specified CSS compatibility styles through the configuration

package.json

"browerslist": { "development": [// set the environment variable:  process.env.NODE_ENV = 'development' "last 1 chrome version", "last 1 firefox version", "last 1 saferi version" ], "Production ": [// default is to look at the production environment ">0.2%", "not dead", "not op_mini all"]}Copy the code

4. Modify the webpack.config.js configuration

{// match files ending in CSS test: /.css$/, // use css-loader for processing, so that webpack can recognize // single loader using loader attributes //loader: 'css-loader' // Multiple loaders need to use the use attribute in reverse order, i.e. the end of the array -> the beginning of the array use: [MiniCssExtractPlugin. Loader, 'CSS - loader', 'postcss - loader]}, {/ / match to less the test at the end of the file: /.less$/, / / less - loader speak less file into the CSS file (need to download the two rely on less and less - loder) / / CSS - loader in the CSS file into a commonjs module is loaded into the js / / style is the inside content strings // use array to execute in backorder, that is, execute 'style-loader' first, When executing 'csS-loader' when executing 'style-loader' use: [MiniCssExtractPlugin. Loader, 'CSS - loader', 'postcss - loader', 'less - loader]}, {/ / match to SCSS the test at the end of the file: /. SCSS $/, use: [MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader', 'sass-loader'] },Copy the code

5, modify index.less

#title{
    color: chocolate;
    opacity: 0.8;
    width: 100px;
    height: 100px;
    transform:rotate(25deg) ;
}
Copy the code

6. Run WebPack

Compress CSS

This is typically done in a production environment, compressing CSS to reduce package size and request time.

From the pit:

Webpackage 5 no longer uses the optimize- CSS -assets-webpack-plugin. This is because the optimis-CSS-assets-webpack-plugin is no longer supported in Webpack 5

What to use?

Using CSS – minimizer – webpack – the plugin

Webpack.docschina.org/plugins/css…

Usage note:

In plugins, webPack compilation uses this plug-in at startup.

2, while configured in “optimization.minimizer”, will only be used when the “optimization.minimizer” feature is enabled.

So WebPack recommends that plug-ins, like the compression class, be configured in the “optimization.minimizer” array.

In order to facilitate unified control through “optimization. Minimizer”. (Minimizer is enabled by default in the production environment)

Use:

1, install,

npm i css-minimizer-webpack-plugin -D
Copy the code

2, modify the optimization. Minimizer configuration in wepack.config.js

optimization: { minimizer: [ new CssMinimizerWebpackPlugin(), ], minimize: // If you also want to enable CSS optimizations in your development environment, set optimization.minimize to true:}Copy the code

3. Run NPM run build

Compile successfully

We can see the build/ CSS /built. CSS file content compression

There was no problem checking the browser

Clear useless CSS

To remove unused CSS, use purgecss-webpack-plugin

www.npmjs.com/package/pur…

use

1, install,

npm i purgecss-webpack-plugin --save-dev
Copy the code

2. Modify the webpack.config.js configuration

const { resolve } = require('path');
const PurgecssPlugin = require("purgecss-webpack-plugin");
const glob = require('glob')
const PATHS = {
    src: resolve(__dirname, 'src')
}
Copy the code
 plugins: [
  
   new PurgecssPlugin({
    paths: glob.sync(`${PATHS.src}/**/*`,  { nodir: true }),
   })
  ]
Copy the code

3. Modify index. CSS to add useless styles

html,
body {
    padding: 0;
    margin: 0;
    background-color: cadetblue;
}
​
.other {
    padding: 0;
    margin: 0;
    background-color: cadetblue;
    display: flex;
    width: 100px;
    height: 100px;
}
Copy the code

4. Run and compile Webpack

We can see build/ CSS /built.css

.other was deleted from

Thank you

This is the end of this introduction, then will be sorted out webpack knowledge system content sharing, enjoy looking forward to, thank you for reading ~~