Webpack4 series tutorial (13) : automatic HTML file generation More welcome to my station to see more original content: godbmw.com, “posture” exchange. (^∇^*)

0. Course introduction and materials

  • >>> This lesson source code
  • >>> All course source code

The code table for this lesson is as follows:

The package.json configuration file of plugin and loader used in this lesson is as follows:

{
  "devDependencies": {
    "file-loader": "^ 1.1.11"."html-loader": "^ 0.5.5"."html-webpack-plugin": "^ 3.2.0"."url-loader": "^" 1.0.1."webpack": "^ 4.16.1"}}Copy the code

1. Why generate HTML automatically?

Those of you who have seen this series of tutorials will know that in the previous example, every time you perform webpack to generate a JS file, you have to manually insert the path to the packed file in index.html.

But in a real production environment, the full index.html should be generated automatically after a single run of Webpack. For example, static resources and JS scripts are automatically inserted.

To achieve this function, HtmlWebpackPlugin needs to generate corresponding HTML files according to the specified index. HTML template, and need to cooperate with htMl-loader to process < IMG > tags and attributes in HTML files.

2. Write entry files

Write the SRC /vendor/sum.js file, encapsulating the sum() function as an example, to be referenced by other files (modular programming) :

export function sum(a, b) {
  return a + b;
}
Copy the code

Write the entry file SRC /app.js, import the sum() function we wrote above, and run it so that we can check the packaging results on the console:

import { sum } from "./vendor/sum";

console.log("1 + 2 =", sum(1.2));
Copy the code

3. Write AN HTML file

The index. HTML in the root directory is used as the template for the HTML file that is eventually generated by html-webpack-plugin. Once packaged, the reference relationships and file paths are added as configured correctly.

<! -- index.html -->

      
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <div></div>
  <img src="./src/assets/imgs/xunlei.png">
</body>
</html>
Copy the code

4. WriteWebpackThe configuration file

As always, HtmlWebpackPlugin is configured in the Plugin option. Common parameter meanings are as follows:

  • Filename: indicates the name of the packaged HTML file
  • Template: template file (index. HTML in the root directory of the source code example)
  • Chunks:entryMatches in the configuration, supporting multiple pages and multiple entries
  • Minify. CollapseWhitespace: compression options

In addition, because in index.html we refer to static files (image types) in the SRC /assets/imgs/ directory. The image needs to be processed with urL-loader and then declared with htMl-loader. Note that urL-loader is processed first, then HTML-loader is processed.

const path = require("path");
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  entry: {
    app: "./src/app.js"
  },
  output: {
    publicPath: __dirname + "/dist/".path: path.resolve(__dirname, "dist"),
    filename: "[name]-[hash:5].bundle.js".chunkFilename: "[name]-[hash:5].chunk.js"
  },
  module: {
    rules: [{test: /\.html$/.use: [{loader: "html-loader".options: {
              attrs: ["img:src"}}]}, {test: /\.(png|jpg|jpeg|gif)$/.use: [{loader: "url-loader".options: {
              name: "[name]-[hash:5].min.[ext]".limit: 10000.// size <= 20KB
              publicPath: "static/".outputPath: "static/"}}]}]},plugins: [
    new HtmlWebpackPlugin({
      filename: "index.html".template: "./index.html".chunks: ["app"].// The app entry in the entry is packaged
      minify: {
        // Compression options
        collapseWhitespace: true}}})];Copy the code

5. Results and tests

Run WebPack to pack and here is the result:

The auto-generated index.html file can be viewed in /dist/, as shown below. Both the script and static resource paths are handled correctly:

Open index.html directly in Chrome and open the console:

The image was successfully inserted into the page, and js ran without error, successful.

6. More information

  • html-loaderDocuments:www.webpackjs.com/loaders/htm…
  • html-webpack-pluginDocuments:www.webpackjs.com/plugins/htm…
  • Webpack4 tutorial (13) : automatic HTML file generation