03-webpack5学习-常用插件html-webpack-plugin

本文详细介绍了如何使用 Webpack 构建一个多页面应用,包括配置 webpack.config.js 文件,设置 entry 入口、output 输出、HtmlWebpackPlugin 插件以及使用 template 模板生成 HTML 文件。通过 excludeChunks 参数排除不需要引入的 JS 文件,实现不同页面独立打包。最后,文章还展示了打包命令及打包后的目录结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

项目结构
webpackHtmlWebpackPlugin
│  package-lock.json
│  package.json
│  webpack.config.js
└─src
        index.js
        mine.js

安装依赖

在webapckHtmlWebpackPlugin目录下运行

npm i webpack webpack-cli htm-lwebpack-plugin --save-dev
webpack.config.js配置文件
const { resolve } = requrie("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
	mode:"development",
	entry:{
		index:"./src/index.js",
		mine:"./src/mine.js"
	},
	output:{
		path:resolve(__dirname,"dist"),
		filename:"[name].build.js"
	},
	plugins:[
		new HtmlWebpackPlugin({
			title:"index的Html文件",
			chunks:["index"]
		}),
		new HtmlWebpackPlugin({
			title:"mine的Html文件",
			excludeChunks:['mine'],
			template:"./public/mineTemplate.html",
			filename:"mine.html"
		})
	]
}
webpack中的关键属性
puligns属性

这个属性接受一个数组,里面的每一项是使用插件的实例对象

html-webpack-plugin常用的option参数
  • title:在不设置template属性的情况下,会将其值在自动生成html的标签中;使用了template后,需要在模板中使用<%=htmlWebpackPlugin.options.title%>作为变量,打包后,值将替换掉<%=htmlWebpackPlugin.options.title%>,可以查看下方的mineTimeplate.html
  • chunks:默认值为"all",即不做设置时,将入口所有的js都引入到对应的html中,但会受到excludeChunks的影响
  • excludeChunks:接受一个字符串数组,每一项字符串数组将匹配entry中的key,如果命中,则对应的html将不会加载这个js
  • template:接受一个字符串路径,在打包时基于这个模板进行打包
  • filename:设置打包后的html文件名,默认值为index.html;如果其中含有[name]字符串,则会根据entry的key值,生成对应key值的html
mineTemplate.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <!-- mine设置的title值将替换掉title标签内的内容 -->
    <title><%=htmlWebpackPlugin.options.title%></title>
  </head>
  <body></body>
</html>

打包命令

  • 方式一:在webpackHtmlWebpackPlugin目录下运行
webpack --config ./webapck.config.js
  • 方式二:在package.json文件的scripts属性新增如下命令
{
	...
	"scripts":{
		"build":"webpack --config ./webpack.config.js"
	}
	...
}

修改保存后,在webpackHtmlWebpackPlugin目录下运行如下命令:

npm run build

打包后的目录

webpackHtmlWebpackPlugin
│  package-lock.json
│  package.json
│  webpack.config.js
├─dist
│      index.build.js
│      index.html
│      mine.build.js
│      mine.html
├─public
│      mineTemplate.html
└─src
        index.js
        mine.js
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值