webpack4从0开始构建前端单页项目(2)用html-webpack-plugin生成html文件

HtmlWebpackPlugin用于创建.html文件。可以使打包的的js、css文件自动被引入生成的html文件中。

安装

    cnpm i html-webpack-plugin -D

项目结构

    project
    |   .editorconfig       # 配置格式化插件
    |   package.json        # 项目需要的依赖
    |   webpack.config.js   # webpack配置文件
    |   
    +---public
    |       index.html      # 用于打包生成 .html 文件的模板
    |       
    ---src
            main.js         # webpack的入口文件

webpack配置文件

// webpack.config.js
    const webpack = require("webpack");
    const path = require("path");
    const htmlWebpackPlugin = require("html-webpack-plugin");

    module.exports = {
        entry: "./src/main.js",
        mode: "development",
        output: {
            path: path.join(__dirname, "dist"),
            filename: "app.[hash:16].js",
        },
        plugins: [
            new htmlWebpackPlugin({
                filename: "index.html", // 打包后生成的html文件的名字
                template: "./public/index.html", // 指定使用哪个html文件为模板,如果不指定会使用默认配置
                minify: {   // 这个对象还可配置第三方插件
                    collapseWhitespace: true, // 设置为true 压缩html,去掉html文件中的空格,换行
                },
                inject: true, // 默认为true,打包和自动引入js、css等文件。  设置为false不会自动引入js、css等文件
                // chunks: ["main"],  用于多入口,指定加载哪些入口文件(chunks),多页应用会用到
            }),
        ],
    };

依赖的模块(package.json)

    "devDependencies": {
        "html-webpack-plugin": "^4.5.0",
        "webpack": "^4.44.2",
        "webpack-cli": "^3.3.12"
    }

配置运行脚本(package.json)

    "scripts": {
        "test": "echo "Error: no test specified" && exit 1",
        "build": "webpack --webpack.config.js"
    }

运行 npm run build 执行打包命令

HtmlWebpackPlugin 参考1: https://webpack.docschina.org/plugins/html-webpack-plugin/

HtmlWebpackPlugin 参考2: https://www.webpackjs.com/plugins/html-webpack-plugin/

HtmlWebpackPlugin 配置参考: https://github.com/jantimon/html-webpack-plugin

开发工具
原文地址:https://www.cnblogs.com/cisbest/p/13745141.html