webpack plugin (插件)
插件给webpack提供了很多方便的功能,在进行打包时,利用插件可以解决我们的很多问题
插件就是普通的nodejs模块,所以使用插件时需要下载,并且在 webpack.config.js
中引入
如何使用插件
// 具体如何引入需要看对应插件的文档
const 插件 = require("插件模块")
module.exports = {
entry: "",
output: {
filename: "",
path
},
plugins: [
new 插件模块({})
]
}
插件列表
clean-webpack-plugin
当我们进行打包时,自动删除上次打包的dist目录,如果不写配置,则需要我们写 output
的 path配置,这样,该插件才会自动删除对应生成的打包文件夹
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
module.exports = {
...,
output: {
filename: '',
path: __dirname + "/dist"
},
plugins: [
new CleanWebpackPlugin()
]
}
html模板插件
下载 html-webpack-plugin
yarn add html-webpack-plugin -D
在项目目录里创建对应的模板,可以创建在 /public/index.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">
<!-- 可以获取到页面中的配置 -->
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
<div>
文字
<p>文字</p>
<i class="iconfont icon-sousuo"></i>
</div>
</body>
</html>
配置插件
module.exports = {
...,
plugins: [
new HtmlWebpackPlugin({
title: '页面的标题',
template: '模板的路径'
}),
// 如果想生成多个页面,继续new
new HtmlWebpackPlugin({
title: '页面的标题',
template: '模板的路径'
}),
]
}