Introduction to webpack Learning Handbook

Posted by LAX on Sun, 21 Jul 2019 06:11:14 +0200

I Weixin Public Number: Front-end practice road, welcome attention.

A couple of days ago, it suddenly occurred to my friends that in less than half a year, the first batch of 20 will be born soon. This feeling is like, now the post-90s look after 60 to accidentally our post-90s in the eyes of the post-20s have become the last century. o()o

It's time to review the webpack series and combine it with a process you use.

css optimization

In my project, I found that sometimes css would duplicate, or I didn't know who wrote a css style that was never used at all. If the file is small, the impact is not very large. But I have a project and found that there are more than 9,000 lines of css in it!

For me with code cleanliness, this is intolerable ~if the file is small, I also have the opportunity to look up lines and delete the redundant code. Unfortunately, this document has too much content. Fortunately, I found a web pack plug-in mini-css-extract-plugin. This plug-in, combined with purifycss-web pack, can meet my needs and give the function to webpack.

mini-css-extract-plugin

The mini-css-extract-plugin plug-in can be used inwebpack plugins See more configuration options. I'll just use the simplest configuration items here.

const MiniCssExtractPlugin = require('mini-css-extract-plugin');

plugins: [
    new MiniCssExtractPlugin({          // css file extraction
        filename: 'css/[name].min.css',    // Specify the name of the extracted file and under the css path
        chunkFilename: 'css/[id].min.css',
    }),
],
module: {
    rules: [
        {
            test: /\.css$/, // Because I only have css code in my project, I only write css regularly.
            use: [
                {
                    loader: MiniCssExtractPlugin.loader, // Specify using mimi-css-extract-plugin
                    options: {
                        publicPath: '../',
                        hmr: process.env.NODE_ENV === 'development',    // Open hmr only in development environments
                    },
                },
                'css-loader',        // Using css-loader
            ],
        }
    ]
}

purifycss-webpack

purifycss-webpack plug-in can goView more configuration items on npm official website.

Note: If you open the npm description of purifycss-webpack plug-in, the page will prompt you to use the extract-text-webpack-plugin plug-in, and the sample code is also demonstrated with this plug-in. But in fact, this plug-in has been abandoned. The recommended use of the official website is the mini-css-extract-plugin plug-in used above.

const glob = require('glob');    // It's important to install glob-all plug-in here instead of glob.
const PurifyCSSPlugin = require('purifycss-webpack');

new PurifyCSSPlugin({       // css file de-duplication
    paths: glob.sync(path.join(__dirname, 'index.html')) // Specify html pages, or match all html using wildcard *
})

Only when purifycss-webpack and mini-css-extract-plugin are used together can CSS be de-duplicated.

optimize-css-assets-webpack-plugin

After re-implementation, the files have been reduced a lot, but I am not satisfied. Because I want to use compressed css online to further reduce file size and save user traffic. If you read the document just now, you will find that MiniCss Extract Plugin is a plug-in that mentions the use of compressed css and js plug-ins in the build environment.

So I just use it directly.

const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const TerserJSPlugin = require('terser-webpack-plugin');

 optimization: {
     minimizer: [new TerserJSPlugin({}), new OptimizeCSSAssetsPlugin({})],   // js compression and css compression
 }

Picture optimization

url-loader

After css extraction and css compression, further optimization can be found. Some small icons and logo s are commonly used in websites. Some small icons will be sprite maps, some will not. Later, by searching, it was found that some small icons can be made into base64, and the small icons can be written into the css file, thus reducing the number of http requests. If you do this process manually, it is more cumbersome. Fortunately, the url-loader plug-in was found. Detailed configuration of plug-ins can be seenwebpack Loaders

module: {
        rules: [
            {
                test: /\.(png|jpe?g|gif|svg)$/i,    // Matched Picture File Types
                use: [
                    {
                        loader: 'url-loader',
                        options: {
                            limit: 1024,  // Make the picture below 1024 into base64 picture, more than no processing
                            name: '[name].[ext]',
                            outputPath: 'img/',
                            publicPath: '../img/'   // After specifying this address, the background in css becomes base64~, and the path uses this path
                        },
                    }
                ]
            }
       ]
}

It should be noted that I modified the following rule /. (png|jpe?g|gif|svg)$/i so that both jpg and jpeg can match. In addition, you need to specify the limit parameter, which means that the image below the limit configuration value is encoded by base64, and no processing is done for the image beyond.

In this process, the problem encountered is that if the picture does not have base64, it will cause the url address referenced in the background picture backgrounds to be incorrect, leading to the failure of the picture reference. Later, after debugging, it was found that by specifying the option. publicPath attribute, it could be referenced correctly.

image-webpack-loader

After processing the small icons, I think I need to deal with the big picture. Because if you only deal with small icons, the impact does not seem to be great. The real traffic is the picture. In fact, when doing the project, the png image will be compressed once. But I used it before.Online tools This is the case. Now I want to use packaging tools to automate processing.

image-webpack-loader can compress png, jpeg, gif, webp, svg. The compression quality of different types of pictures can be specified separately.

                    {
                        loader: 'image-webpack-loader',
                        options: {
                            mozjpeg: {
                                progressive: true,
                                quality: 65
                            },
                            // optipng.enabled: false will disable optipng
                            optipng: {
                                enabled: false,
                            },
                            pngquant: {
                                quality: '65-90',
                                speed: 4
                            },
                            gifsicle: {
                                interlaced: false,
                            },
                            // the webp option will enable WEBP
                            webp: {
                                quality: 75
                            }
                        }
                    }

After using this plug-in, I did find that my picture has been reduced a lot.

Overall configuration

It simply lists the various loader s and plugin s that need to be used. But the whole configuration is not complete. The complete webpack-config.js code is as follows:

const path = require('path');
const glob = require('glob');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const TerserJSPlugin = require('terser-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const PurifyCSSPlugin = require('purifycss-webpack');

module.exports = {
    mode: 'production',
    entry: {
        style: './js/style.js',
    },
    optimization: {
        minimizer: [new TerserJSPlugin({}), new OptimizeCSSAssetsPlugin({})],   // css compression
    },
    plugins: [
        new CleanWebpackPlugin(),               // File clearance
        new MiniCssExtractPlugin({          // css file extraction
            filename: 'css/[name].min.css',
            chunkFilename: 'css/[id].min.css',
        }),
        new PurifyCSSPlugin({       // css file de-duplication
            paths: glob.sync(path.join(__dirname, 'index.html')),
        })
    ],
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [
                    {
                        loader: MiniCssExtractPlugin.loader,
                        options: {
                            publicPath: '../',
                            hmr: process.env.NODE_ENV === 'development',
                        },
                    },
                    'css-loader',
                ],
            },
            {
                test: /\.(png|jpe?g|gif|svg)$/i,
                use: [
                    {
                        loader: 'url-loader',
                        options: {
                            limit: 1024,
                            name: '[name].[ext]',
                            outputPath: 'img/',
                            publicPath: '../img/'   // After specifying this address, the background in css becomes base64~, and the path uses this path
                        },
                    },
                    {
                        loader: 'image-webpack-loader',
                        options: {
                            mozjpeg: {
                                progressive: true,
                                quality: 65
                            },
                            // optipng.enabled: false will disable optipng
                            optipng: {
                                enabled: false,
                            },
                            pngquant: {
                                quality: '65-90',
                                speed: 4
                            },
                            gifsicle: {
                                interlaced: false,
                            },
                            // the webp option will enable WEBP
                            webp: {
                                quality: 75
                            }
                        }
                    }
                ],
            }
        ],
    },
    output: {
        filename: '[name].min.js',
        path: path.resolve(__dirname, './dist')
    }
};
  • The entry entry entry to the file is style.js.
  • All packaged file directories are specified by output.path and exported to the dist directory.
  • When configuring loaders, you can configure multiple loaders under a regular match. For example, I configure url-loader first, and then image-webpack-loader.

In the entry file style.js, nothing is actually done, but the introduction of the need to use the css file. The code is as follows:

import style from '../css/style.css';

So the process is style.js introduces style.css, and then web packages are packaged to generate style.min.js and style.min.css.

The overall project structure is as follows:

That's one case where I use webpack in my project. At present, this introductory learning handbook is over here.

(End)

Related articles

Introduction to webpack learning handbook (1)

Introduction to webpack learning handbook (2)

Introduction to webpack learning handbook (3)

Introduction to webpack learning handbook (4)

Topics: Javascript Webpack npm less Attribute