Webpack 是一个强大的打包工具,但是在打包过程中需要处理很多文件,尤其是在构建多页应用时,需要处理多个 HTML 文件。这时候就需要使用 html-webpack-plugin 插件来自动生成 HTML 文件。
插件介绍
html-webpack-plugin 是一个能够根据模板自动生成 HTML 文件的 Webpack 插件。它可以将打包后的 JS 和 CSS 文件自动注入到 HTML 文件中,并且可以配置一些参数来定制生成的 HTML 文件。
安装
使用 npm 安装 html-webpack-plugin:
npm install --save-dev html-webpack-plugin
使用
在 Webpack 配置文件中引入 html-webpack-plugin:
const HtmlWebpackPlugin = require('html-webpack-plugin');然后在 plugins 中添加 html-webpack-plugin:
plugins: [
new HtmlWebpackPlugin({
title: 'My App',
template: './src/index.html'
})
]这样就可以在打包后的 dist 目录中生成一个 index.html 文件,并且自动注入打包后的 JS 和 CSS 文件。
配置参数
html-webpack-plugin 支持很多配置参数,下面介绍一些常用的配置:
title
指定生成的 HTML 文件的标题。
new HtmlWebpackPlugin({
title: 'My App'
})template
指定 HTML 模板文件的路径。
new HtmlWebpackPlugin({
template: './src/index.html'
})filename
指定生成的 HTML 文件的名称,默认为 index.html。
new HtmlWebpackPlugin({
filename: 'my-index.html'
})inject
指定打包后的 JS 和 CSS 文件注入到 HTML 文件的位置。默认为 true,即注入到 body 底部。
new HtmlWebpackPlugin({
inject: 'head'
})minify
压缩生成的 HTML 文件。默认为 false。
new HtmlWebpackPlugin({
minify: {
collapseWhitespace: true,
removeComments: true
}
})chunks
指定需要注入到 HTML 文件中的打包后的 JS 文件。默认为 all,即所有打包后的 JS 文件。
new HtmlWebpackPlugin({
chunks: ['app']
})示例代码
下面是一个完整的 Webpack 配置文件示例,用于构建一个多页应用:
// www.javascriptcn.com code example
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
app: './src/app.js',
about: './src/about.js'
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].[contenthash].js'
},
plugins: [
new HtmlWebpackPlugin({
title: 'My App',
template: './src/index.html',
filename: 'index.html',
chunks: ['app']
}),
new HtmlWebpackPlugin({
title: 'About',
template: './src/about.html',
filename: 'about.html',
chunks: ['about']
})
]
};这个配置文件将会生成两个 HTML 文件,分别为 index.html 和 about.html,它们都会自动注入打包后的 JS 文件。其中 index.html 只会注入 app.js,而 about.html 只会注入 about.js。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67d23301a941bf713442f66d