webpack4.0基础(二)

Plugins

扩展 webpack 本身的一些功能,它们会运行在各种模块解析完成以后的打包编译阶段,比如对解析后的模块文件进行压缩等 。

1. html-webpack-plugin

在打包结束后,自动生成一个 html 文件,并把打包生成的 js 模块引入到该 html 中 。

官网:https://www.webpackjs.com/plugins/html-webpack-plugin/

安装:
$ yarn add html-webpack-plugin -D
OR
npm install --save-dev html-webpack-plugin

在webpack.config.js中使用:

let HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
...,
//=>在webpack中使用插件
    plugins: [
        new HtmlWebpackPlugin({
            //=>指定自己的模板
            //=> 指定生成 html 的模版文件(如果不指定,则会生成一个默认的不附带其它内容的 html 文件)
            template: './src/index.html',
            //=>输出的文件名
            filename: 'index.html',
            //=>给引入的文件设置HASH戳(清除缓存的),也可以在output中设置 filename: 'bundle.min.[hash].js' 来生成不同的文件
            hash: true,
            //=>控制是否以及以何种方式最小化输出
        //=>https://github.com/kangax/html-minifier
            minify: {
                collapseWhitespace: true,
                removeComments: true,
                removeAttributeQuotes: true,
                removeEmptyAttributes: true
            }
        })
    ]
}
在 html 模板中,可以通过 <%=htmlWebpackPlugin.options.XXX%> 的方式获取配置的值 :
new HtmlWebpackPlugin({
			title:"My App",
			...
			})
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title><%=htmlWebpackPlugin.options.title%></title>
</head>

2. clean-webpack-plugin

删除(清理)构建目录

yarn:https://classic.yarnpkg.com/zh-Hans/package/clean-webpack-plugin
npm:https://www.npmjs.com/package/clean-webpack-plugin

安装:
yarn add clean-webpack-plugin -D
OR
npm i clean-webpack-plugin -D

// webpack.config.js
const { CleanWebpackPlugin } = require('clean-webpack-plugin')

module.exports = {
  plugins: [new CleanWebpackPlugin({
    cleanOnceBeforeBuildPatterns: [path.resolve(__dirname, 'dist')] 
    // 若不配置,默认删除 output 下 path 指定的目录
  })]
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值