This is the sixth day of my participation in the First Challenge 2022. For details: First Challenge 2022.

Through the first two articles “WebPack 5 tutorial 1: Introduction to Webpack”, “WebPack 5 tutorial 2: Resource module and loader” learning, we have been able to use Webpack to achieve all the resource file loading and packaging, but packaging completed how to demonstrate the effect?

What we did was create an HTML file ourselves, and then manually import the packaged main.js file,

    <! DOCTYPEhtml>
    <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>Webpack</title>
        </head>
        <body>
            <script src="./main.js"></script>
        </body>
    </html>
Copy the code

However, there is a problem with this: if the file name is main.js every time it is packaged, there will be a caching problem when it goes live and the page will not be updated.

As we learned earlier, we can solve the browser cache problem by adding a hash character to output.filename to generate a different filename each time

    module.exports = {
        / /...
        output: {/ /...
            filename:'bundle-[hash:5].js'}}Copy the code

However, there is another problem: because the name of the package file is different each time, it is very tedious to reintroduce the JS file into the HTML code each time

    <script src="./bundle-9034a.js"></script>
Copy the code

Is there an operation that automatically imports JS files after packaging? The answer is the plugin, which is the main content of this article. Let’s talk about the use of the WebPack plug-in first, and then solve the above problems

What is the WebPack Plugin

Loader is used to solve the problem of resource file loading and compilation, it only works in the module loading link, and Plugin is used to deal with the automation work other than Loader: Plugin is used to increase Webpack’s ability to automate the build of projects, and can be used in all aspects of Webpack workflow. It is Plugin that makes Webpack almost omnipotent

What can plug-ins do

  • Automatically generate the required HTML files
  • Clear the contents of the dist output directory before implementing packaging
  • Copy resource files that do not need to be packaged to the output directory
  • Compress the webPack packed output file
  • Automated deployment
  • .

Next we’ll use three plug-ins to address the use of plug-ins

1. HTML file generated by Webpack plugin:html-webpack-plugin

To generate AN HTML file, for example, we need to use the HTML-webpack-plugin, which is a necessary plug-in for almost all Webpack-based projects. Next, we use it to implement the above problem: generate the HTML file and automatically import the packaged JS file

  1. Installing a plug-in

        npm install html-webpack-plugin
    Copy the code
  2. Configuring the use of webPack plugins is implemented by instantiation (new plugins for as many HTML files as possible). The following code generates an HTML file in the output directory (default is index.html) and automatically imports the packaged JS file

        const HtmlWebpackPlugin = require('html-webpack-plugin')
        module.exports = {
            / /...
            plugins: [new HtmlWebpackPlugin()
            ]
        }
    Copy the code

The generated index.html file also automatically imports the generated JS file.

  1. Configuration options:

    • Template: Specifies that the default HTML file generated by the template is an empty HTML file,bodyIf you want to generate an HTML file with a specific structure, you can passtemplateOption specifies that the module creates an HTML file, which can be passed in the template<% htmlWebpackPlugin.options.xx %>The configuration information is obtained
    • Filename: Specifies the name of the HTML file to be generated.index.html) for multi-page applications, used to generate multiple files
    • Chunks: HTML file specifies the import module for multi-page applications. By default, the generated HTML file will import all the packaged files. You can specify the import file through this setting
    • Title: Specifies the title to generate the HTML file
        module.exports = {
            / /...
            plugins: [new HtmlWebpackPlugin({
                    template:'./src/index.html'
                }),
                new HtmlWebpackPlugin({
                    title:'Login page'.template:'./src/index.html'.filename:'login.html'}})]Copy the code
        <! -- ./src/index.html -->
        <! DOCTYPEhtml>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta http-equiv="X-UA-Compatible" content="IE=edge">
            <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
            <title><%= htmlWebpackPlugin.options.title %></title>
        </head>
        <body>
            <div id="app"></div>
        </body>
        </html>
    Copy the code

    The generated effect is as follows:

2. Output directory of Webpack plugin: clean-webpack-plugin

As you can see from the screenshot above, webPack generates corresponding files (including some image files) in the dist directory every time it is packaged. As the files generated may be different each time, many files will be generated in this directory over time, making it difficult to manage

We can use the clean-webpack-plugin to clean previously generated files before packaging as follows:

   const { CleanWebpackPlugin } = require('clean-webpack-plugin');
    module.exports = {
        / /...
        plugins: [new CleanWebpackPlugin()
        ]
    }
Copy the code

Run the Webpack package, every time you can clean up the previous file, mom no longer worry about me looking for the wrong file ~~

PS: There is an easier way to automatically clean the output directory, but only WebPack 5.20.0 or later supports it. Just set output.clean to true. Embrace webpack5

    module.exports = {
        output: {/ /...
            clean:true}}Copy the code

3, Webpack plugin to copy resources that do not need to be processed by Webpack: copy-webpack-plugin

There are also many files that don’t need to be built by WebPack in real development (e.g. Favicon. ico, robots.txt, etc.), these files need to be deployed to the server eventually, so they also need to be put in the final output directory, you can use copy-webpack-plugin to copy, avoid manual operation, configuration code is as follows:

   const CopyPlugin = require("copy-webpack-plugin");
    module.exports = {
        / /...
        plugins: [
             new CopyPlugin({
                patterns: [
                    // Copy the public folder to the output directory
                    './src/public'.// Copy assets to the imgs folder in the output directory
                    { from: "./src/assets".to: "imgs"},],}),],}Copy the code

conclusion

In fact, there are hundreds of Webpack plugins, but they are all similar in use. The difference is that their configuration parameters are different. Once we understand the commonality of these plugins, it is not difficult to use other plugins. You can consult the documentation on the official website to see the configuration parameters of other plug-ins