使用 webpack 自动生成html文件


作者:Seiya

时间:2019年07月11日


为什么要自动生成 HTML


在真实生产环境中,一次运行 webpack 后,完整的 index.html 应该是被自动生成的,静态资源、js 脚本都被自动插入了。为了实现这个功能,需要借助 html-webpack-plugin 根据指定的 index.html 模板生成对应的 html 文件,还需要配合 html-loader 处理 html 文件中的 <img> 标签和属性。



编写 Webpack 配置文件


html-webpack-plugin 是在 plugin 这个选项中配置的。常用参数含义如下:

  • filename:打包后的 html 文件名称

  • template:模板文件(例子源码中根目录下的 index.html)

  • chunks:和 entry 配置中相匹配,支持多页面、多入口

  • minify.collapseWhitespace:压缩选项


除此之外,因为我们在 index.html 中引用了 src/assets/imgs/ 目录下的静态文件(图片类型)。需要用 url-loader 处理图片,然后再用 html-loader 声明。注意两者的处理顺序,url-loader 先处理,然后才是 html-loader 处理。具体配置如下:

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"], // entry中的app入口才会被打包
      minify: {
        // 压缩选项
        collapseWhitespace: true
      }
    })
  ]
};

编写完成后,通过命令行进行打包,可以在 /dist/ 目录中查看自动生成的 index.html 文件,脚本和静态资源路径都被正确处理了。

最后更新时间: 2019-7-11 20:32:07