将打包好的js文件引入到html中

将JS包引入到html文件

webpack根据入口文件,解析里面使用import或者require引入的模块,将引入的模块打包到一个js文件中。
步骤1完成了JS打包,需要引入到html文件中才能使用
需要将生成的js文件自动引入html文件中

使用到插件:
html-webpack-plugin

  1. 安装插件

    1
    npm i html-webpack-plugin --save-dev
  2. 配置 webpack.config.js

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    //+++
    //引入插件
    const HtmlWebpackPlugin = require('html-webpack-plugin');
    //+++

    const config = {
    entry:'./src/main.js',
    output: {
    filename:'bundle.js',
    path: path.resolve(__dirname,'dist')
    },
    //+++
    //配置插件
    //plugins,插件数组。需要使用的插件都添加到这个数组中
    plugins:[
    new HtmlWebpackPlugin()
    ]
    //+++
    }
  3. 更改main.js,以便查看效果
    增加

    1
    document.body.style.background = 'red';
  4. 执行

    1
    npm run start

    dist目录下会生成:
    bundle.js
    index.html

    浏览器打开index.html,显示红色页面
    index.html由 HtmlWebpackPlugin 插件自动生成,并将bundle.js插入到页面中

  5. 使用自己的html文件
    配置 HtmlWebpackPlugin

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
        new HtmlWebpackPlugin({
    template:'index.html' //自定义html文件的路径和名称
    })
    ```
    生成的js会自动插入到body标签的最后


    # 详细配置
    具体可参考 [github html-webpack-plugin](https://github.com/jantimon/html-webpack-plugin#)

    ```js
    new HtmlWebpackPlugin({
    title:'test', //设置标题,默认为'Webpack App'
    filename:'index.html', //输出的文件名,默认为'index.html'
    template:'index.html', //模版文件名,默认为''
    templateParameters:{//模版中的参数配置
    testName:'123'
    },
    inject:true,//注入到页面中的位置,默认为true:注入到body标签底部
    minify:true //压缩,默认为false
    })

本文地址: http://gehaiqing.com/2018/07/06/webpack-2-inject-html/