解析 html 文件
了解插件
❝在解析打包 HTML 之前,先要了解 webpack 中的 plugin
❞
- 想要使用插件首先要安装插件
- 然后在 webpack.config.js 里面引入
- 然后在 plugins 里面使用
❝
「webpack.config.js」里面的plugins是一个数组,里面放着许多的插件
❞
安装 html-webpack-plugin
- 「html-webpack-plugin」插件是为应用生成一个 html 文件,并自动引入打包后的文件
yarn add html-webpack-plugin -D
引入和使用
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
mode: 'development',
devServer: {
contentBase: path.join(__dirname, 'dist'),
compress: true,
port: 3000,
open:true,
progress :true
},
entry: './src/index.js',
output: {
filename: 'build.js',
path: path.resolve(__dirname, 'dist')
},
plugins:[
new HtmlWebpackPlugin()
]
}
- 运行「npm run build」 会发现 dist 文件夹里面有一个「index.html」,并把打包后的 js 引入了
- 「html-webpack-plugin」也可以传入一个对象为参数
- 「title」:生成 html 文件的标题
- 「filename」:生成 html 文件的名字,默认是 index.html
- 「template」:指定生成所依赖的哪一个 html 文件模板,可以是 html 文件,ejs 文件,jade 文件
- 「favicon」:页面图标
- 「minfiy」:是否进行页面压缩。布尔值,默认是 fasle
- 「chunks」:用于多入口文件
plugins:[
new HtmlWebpackPlugin({
title:'测试',
minify:false,
template:path.resolve(__dirname,'src/index.html'),
filename:'test.html'
})
]
- 在「src」目录下新建一个 index.html
❝在控制台输入 npm run build 之后发现 dist 目录里多了一个 test.html 文件
❞