Webpack: HTML Webpack Plugin

        The HTML Webpack Plugin is used to simplify the creation of the index.html file in the front-end project built by Webpack, so as to avoid the tedious steps of manually creating/copying the index.html to the packaging directory after the project is packaged. Let's start with a phenomenon in a built Vue project and learn more about the use of this plugin step by step.

Table of contents

Talking from index.html in the Vue project

Webpack: Introducing the HTML Webpack Plugin

Webpack: Automatically import scripts and project packaging problems

Other configurations for the HTML Webpack Plugin

 title title

 filename file name

 template file template source

 templateContent custom template attribute

 templateParameters template parameter attribute

​ publicPath property

 scriptLoading script loading method property

 favicon icon properties

 mate attribute

 minify attribute

 hash hash attribute

 showErrors property


Talking from index.html in the Vue project

When we use vue-cli to build a Vue front-end application, the basic content of         the generated index.html is as follows.

<!DOCTYPE html>
<html lang="">
  <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">
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
    <title><%= htmlWebpackPlugin.options.title %></title>
  </head>
  <body>
    <noscript>
      <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
    </noscript>
    <div id="app"></div>
    <!-- built files will be auto injected -->
  </body>
</html>

        Please observe the above code structure carefully. In the standard html page skeleton template, the body contains a DOM element whose id selector value is app for mounting the Vue instance. Other than that, there is no introduction of any JavaScript scripts.

        Let's look at another index.html file located in the output directory after packaging, the content is as follows,

<!DOCTYPE html>
<html lang="">

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <link rel="icon" href="favicon.ico">
  <title>cesium-viewer</title>
  <link href="js/about.b241abde.js" rel="prefetch">
  <link href="css/chunk-vendors.b7dbb5dd.css" rel="preload" as="style">
  <link href="css/index.d52c5618.css" rel="preload" as="style">
  <link href="js/chunk-vendors.b8df0be2.js" rel="preload" as="script">
  <link href="js/index.224fd61e.js" rel="preload" as="script">
  <link href="css/chunk-vendors.b7dbb5dd.css" rel="stylesheet">
  <link href="css/index.d52c5618.css" rel="stylesheet">
</head>

<body><noscript><strong>We're sorry but cesium-viewer doesn't work properly without JavaScript enabled. Please enable it
      to continue.</strong></noscript>
  <div id="app"></div>
  <script src="js/chunk-vendors.b8df0be2.js"></script>
  <script src="js/index.224fd61e.js"></script>
</body>

</html>

        It can be seen that in the HTML file automatically generated after packaging, two script tags are automatically introduced for us to link the JavaScript script file generated by packaging. Seeing this, you may naturally think of the HTML Webpack Plugin plug-in we mentioned at the beginning, because this plug-in also has such capabilities, which is what we want to talk about next.

Webpack: Introducing the HTML Webpack Plugin

        The GitHub official website address of the HTML Webpack Plugin plugin is: https://github.com/jantimon/html-webpack-plugin , the introduction is also very concise: Plugin that simplifies creation of HTML files to serve your bundles (a service for bundles, using plugin to simplify HTML file generation).

        If you want to introduce the plug-in in the Webpack project, you must first pay attention to the Webpack version of the current project, which can be viewed from the package.json file, as shown in the figure below, mine is webpack 5.x version.

         Refer to the introduction on the official website, and use the corresponding command of Webpack5 to install it.

# Webpack 5
  npm i --save-dev html-webpack-plugin
  yarn add --dev html-webpack-plugin
# Webpack 4
  npm i --save-dev html-webpack-plugin@4
  yarn add --dev html-webpack-plugin@4

        Although the official website introduces that this plug-in is zero-configuration, in order to be compatible with our Webpack project, it is still necessary to modify the configuration file of the Webpack project and import the plug-in, as shown below,

const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin') //引入html-webpack-plugin 插件

...

module.exports = {
    ...

    plugins:[
        new HtmlWebpackPlugin({
          filename: `index.html`, //生成的文件名
          template: path.resolve(__dirname, `src/index.html`), //源文件的绝对路径
        }),
    ]
    ...
}

Webpack: Automatically import scripts and project packaging problems

        After introducing the HTML Webpack Plugin plug-in, and then carry out the packaging operation of the project, the plug-in will automatically generate an index.html file for us. The content of the file is as follows,

<!doctype html>
<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">
  <title>webpack-demo</title>
  <script src="index.js"></script>
  <script defer="defer" src="index.js"></script>
</head>

<body>
  <div id="app"></div><input placeholder="input..."> <span class="iconfont">&#xf0012;</span>
  <ul>
    <li>这是第1个li</li>
    <li>这是第2个li</li>
    <li>这是第3个li</li>
    <li>这是第4个li</li>
    <li>这是第5个li</li>
    <li>这是第6个li</li>
  </ul>
  <div id="box"></div>
</body>

</html>

Tips: The defer='defer' attribute in the script tag means: tell the browser that the external JavaScript script file should be downloaded/imported immediately, but execution should be postponed until the entire HTML page is parsed. Note that the defer attribute is only valid for external script files.

         For comparison, let's look at the original file content (below),

<!DOCTYPE html>
<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>webpack-demo</title>
  <!-- <script src="./index.js"></script> -->
  <!-- <script src="../dist/main.bundle.js"></script> -->
  <script src="index.js"></script>
</head>
<body>
  <div id="app"></div>
  <input type="text" placeholder="input...">
  <span class="iconfont">&#xf0012;</span>
  <ul>
    <li>这是第1个li</li>
    <li>这是第2个li</li>
    <li>这是第3个li</li>
    <li>这是第4个li</li>
    <li>这是第5个li</li>
    <li>这是第6个li</li>
  </ul>
  <div id="box"></div>
</body>
</html>

        It can be seen that, similar to the Vue project after packaging, the HTML Webpack Plugin step by step generates the index.html file for us, and automatically introduces the packaged "index.js" entry file into the file.

        We try to deploy it under the Tomcat server,

         Next, start the Tomcat server, access the /webpack-demo front-end project, open the developer tools panel,

         It seems that there is some problem, that is, our console.log statement is printed twice.

        Why is this? We played back the packaged code snippet and found that the index.js entry file was introduced twice, among which: the first script tag was manually introduced when we initially built the project; the second script tag was automatically introduced by the HTML Webpack Plugin introduced. However, both script tags point to the index.js entry file. This is also what causes it to execute twice.

       In fact, this point is also mentioned in the GitHub page of HTML Webpack Plugin. The screenshot is as follows, that is, the plugin will automatically generate HTML files with script tags.

        So, in order to solve this problem, we need to comment out the statements in the source index.html file, and then repackage.

         After packaging, we redeployed to check the number of executions. It is indeed only executed once, and the problem is solved.

 Other configurations for the HTML Webpack Plugin

        Let's continue to look at the GitHub page of the HTML Webpack Plugin plugin to learn about other configuration items.

title title

        The title configuration item can configure the title content for the HTML page generated by the plugin.

        An example is as follows,

 filename file name

        The filename attribute can be used to configure the file name of the generated HTML file, the default is: index.html

 template file template source

        template attribute, specify a path for it (relative path or absolute path can be used). It can be used to configure which HTML file to generate the HTML file for packaging output.

 templateContent custom template attribute

        The templateContent attribute is used to replace the template attribute, make it invalid, and convert it to the template content specified by the templateContent attribute.

         An example of usage is as follows,

 templateParameters template parameter attribute

        The templateParameters attribute is used to specify parameter values ​​for the parameter names in the custom templateContent template source. It is similar to the operation of specifying the title title attribute for the generated HTML file at the beginning, it is the same.

        An example of usage is as follows,

publicPath property

        This attribute is used to specify the parent path for script and link tags in HTML, and it is recommended to use the default value of auto.

 scriptLoading script loading method property

        The scriptLoading attribute is used to specify the loading method of the scirpt script, and the defer non-blocking loading method is used by default.

 

 favicon icon properties

        The favicon attribute is used to configure the icon for the page.

         For example, we want to configure a Vue icon for the Vue project built by Webpack, the configuration is as follows,

 new HtmlWebpackPlugin({
      title: `Webpack-Demo`, //标题
      filename: `index.html`, //生成的文件名
      template: path.resolve(__dirname, `src/index.html`), //源文件的绝对路径
      scriptLoading: 'defer', //以非阻塞的方式加载script脚本
      favicon: path.resolve(__dirname, `src/favicon.ico`), //配置网站图标
    }),

mate attribute

        It is used to configure the meta attribute of the HTML page, corresponding to the Object object type. Defaults to an empty object.

         The following are the default meta attributes,

         The following are the configured meta attributes,

 minify attribute

        The minify attribute is often used for resource file compression operations during project packaging.

 hash hash attribute

         After configuration, the packaged external resource will add a character code by default.

showErrors property

        This property controls whether error details can be displayed in the HTML page as a closeable panel. Enabled by default.

         The effect is as follows,

Guess you like

Origin blog.csdn.net/weixin_43524214/article/details/128726472