Webpack插件之html-webpack-plugin

186 阅读1分钟

为什么要用

我们都知道,通过webpack打包会生成最终的bundle.js,然后我们需要新建一个index.html,并在该文件中引用打包后的文件

<script src='./bundle.js' type='text/javascript' ></script>

这样有一个问题,如果我们打包后的bundle.js名称并不固定,可能会有hash值,我们每次打包后需要手动修改引用语句,有点麻烦,这事完全可以交给webpack来做,html-webpack-plugin就是可以通过我们定义的一个html模板生成index.html并自动引用打包后的文件

如何使用

安装

npm install html-webpack-plugin --save-dev

配置

const htmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
    // 
    plugins: [
        new htmlWebpcakPlugin({
            filename:'index.html', // set the filename
            template:'/src/index.html' //  set the template path
        })
    ]
}

详细options看这里 html-webpack-plugin配置