配置
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
index: './src/index.js',
},
output: {
path: __dirname + '/release',
filename: './bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules)/,
loader: 'babel-loader'
},
{
test: /\.html$/,
loader: 'html-loader'
}
],
},
plugins: [
new HtmlWebpackPlugin({
template: 'template/index.html'
})
],
};
注意点
output.path 很重要,这个路径直接决定你输出的文件的 根目录,
生成html:
需要使用html-loader先对html文件解析,这个主要针对使用html-webpack-plugin插件的template配置,虽然默认html文件不需要解析,但是官方文档对.html类型文件有一句不被注意的说明:
Be aware, using .html as your template extention may unexpectedly trigger another loader.
请注意,使用.html作为模板扩展可能会意外触发另一个加载器。
在看到这句话之前,我就遇到了问题:
解析模板index.html报错
一开始我以为是wepack4.x 与 html-webpack-plugin 插件版本不匹配,折腾了半天没有卵用,然后百度google各种搜(发现webpack4.0废弃了html-webpack-plugin插件,而且把webpack-cli拆出来单独维护,导致项目里使用webpack就必须再安装webpack-cli,所以我果断选择了webpack3.x)。最后还是要仔细看看文档,发现可能是触发了其他loader,导致html文件解析失败,然后使用了html-loader后问题就解决了。
html-webpack-plugin插件:默认filename是./index.html,这个./是基于output.path路径,所以output.path很重要。
这样就生成了一个html文件,并且自动引入了打包后的js文件。