01和02都需要我们自己去创建一个index.html去引入打包后的bundle,现在我们用webpack自动生成index.html,并为我们自动去引入所有的bundle
1.创建一个index.html:(这个文件我放在最外层的,和webpack.config.js同级)
webpack studyhello webpack
2.安装一个webpack插件:
npm i html-webpack-plugin -D
3.在webpack.config.js的plugin中引入html-webpack-plugin插件并进行配置,指向我们的创建好的index.html,让webpack将它作为模板:
这个插件默认会创建一个空的HTML文件,自动引入打包输出的所有资源(这里会自动引入生成的built.js);如果是自定义html文件,那么webpack会复制这个index.html文件到build文件下,然后自动引入bundle
const HtmlWebpackPlugin = require('html-webpack-plugin') //引入插件
module.exports={
//省略了其他配置...
plugins:[
new HtmlWebpackPlugin({
template:'./index.html' //使用我们自定义的作为模板
})
],
}
4.运行webpack
5.此时可以看到在build目录下已经生成了一个index.html ,并为你默认帮你引入了资源
image.png