用webpack构建项目(2)-处理html文件

安装html-webpack-plugin

    npm i html-webpack-plugin -D

项目目录结构

F:\webpack-demo
    ├── dist/               <!-- 打包后生成的目录 -->
    |  ├── index.html       <!-- 打包后生成的html文件 -->
    |  └── main.js          <!-- 打包后生成的js文件 -->
    ├── package.json
    ├── public/             <!-- html模板所在目录 -->
    |  └── index.html       <!-- html模板 -->
    ├── src/
    |  └── index.js
    └── webpack.config.js

配置webpack.config.js

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

    module.exports = {
        mode:"production",          // 模式(mode):webpack 使用相应模式的内置优化
        entry: "./src/index.js",    // 入口(entry):webpack打包的入口
        output: {                   // 输出(output):webpack编译打包后的文件输出的位置
            filename: 'main.js',
            path: path.resolve(__dirname, 'dist'),
        },
        plugins:[                   // 插件(plugin):打包优化,资源管理,注入环境变量。
            new HtmlWebpackPlugin({
                title:"webpack-笔记",                // 用于生成的HTML文档的标题
                filename: "index.html",             // 指定打包生成html文件的名称
                template: "./public/index.html",    // 指定使用哪个html文件为模板,如果不指定会使用默认配置
                minify: {                           // 优化html-webpack-plugin生成的html文件
                    collapseWhitespace: true,       // 设置为true 压缩html,去掉html文件中的空格,换行
                },
                inject: true,                       // 默认为true,打包和自动引入js、css等文件。  设置为false不会自动引入js、css等文件
                // chunks: ["main"],  用于多入口,指定加载哪些入口文件(chunks),多页应用会用到
            })
        ]
    };

打包js和html文件

    npm run build

html-webpack-plugin参考:

https://github.com/jantimon/html-webpack-plugin
https://www.npmjs.com/package/html-webpack-plugin
webpack插件

posted @ 2019-08-02 22:17  氵灬  阅读(69)  评论(0编辑  收藏  举报