前言
Loader是解决Webpack中的资源加载问题,而Plugin则是解决除了资源加载之外的其他自动化工作
用途
- 清除之前的打包文件(dist目录)
- 拷贝静态文件至输出目录
- 压缩打包代码
…
常用插件
- clean-webpack-plugin:清除旧的打包文件
yarn add clean-webpack-plugin --dev
或者
npm install clean-webpack-plugin --dev
import { CleanWebpackPlugin } from 'clean-webpack-plugin'
module.exports = {
...
plugins: [
new CleanWebpackPlugin()
]
...
}
-
html-webpack-plugin:自动生成HTML文件
html自动生成至打包的输出目录
可以自定义html的配置-title:html的标题
-meta: meta标签
-template:html模版
yarn add html-webpack-plugin --dev
或者
npm install html-webpack-plugin --dev
import { CleanWebpackPlugin } from 'clean-webpack-plugin'
import HtmlWebpackPlugin from 'html-webpack-plugin'
module.exports = {
...
plugins: [
new CleanWebpackPlugin()
new HtmlWebpackPlugin({
title: 'Html Webpack Plugin',
meta: {
viewport: 'width=device-width'
},
//自定义一个html模版,模版里面需要读取html webpack plugin的配置项,例:<%= htmlWebpackPlugin.options.title %>
template: './src/index.html'
})
]
...
}
- copy-webpack-plugin:拷贝静态文件至输出目录
yarn add copy-webpack-plugin --dev
或者
npm install copy-webpack-plugin --dev
import { CleanWebpackPlugin } from 'clean-webpack-plugin'
import HtmlWebpackPlugin from 'html-webpack-plugin'
const CopyWebpackPlugin = require('copy-webpack-plugin')
module.exports = {
...
plugins: [
new CleanWebpackPlugin()
new HtmlWebpackPlugin({
title: 'Html Webpack Plugin',
meta: {
viewport: 'width=device-width'
},
//自定义一个html模版,模版里面需要读取html webpack plugin的配置项,例:<%= htmlWebpackPlugin.options.title %>
template: './src/index.html'
}),
new CopyWebpackPlugin([
'public' //可以是通配符(public/**)、目录、文件的相对路径
])
]
...
}
Plugin的工作机制
插件是通过往webpack的生命周期的钩子函数挂载函数实现扩展的~
Webpack的插件机制,其实就是软件开发中的钩子机制,类似于 Web中的事件。在Webpack中有很多的工作环节,为了便于插件的扩展,Webpack给每个环节都埋下了钩子,然后在开发插件时,就可以在每一个不同的节点上去挂载不同的任务,去扩展webpack的能力。
Webpack规定Plugin必须是一个函数或者一个包含apply方法的对象。
手写一个Plugin
plugin作用:删除调打包文件中多余的注释
未使用自定义插件的打包文件效果:
class MyPlugin {
apply(compiler){ //compiler是webpack工作中最核心的一个对象,也是通过这个对象来注册一个钩子
//找到webpack中的emit钩子,通过tap注册一个钩子,接受两个参数:参数名称和挂载到钩子上的函数
compiler.hooks.emit.tap('MyPlugin', compilation => {
//compilation - 可以理解为打包的上下文
for(const name in compilation.assets){ //assets - 资源文件信息
if(name.endWith('.js')){
const contents = compilation.assets[name].source()
const withoutComments = contents.replace(/\/\*\*+\*\//g, '')
compilation.assets[name] = {
source: () => withoutComments,
size: withoutComments.length //size为必填字段
}
}
}
})
}
}
module.exports = {
...
plugins: [
...
new MyPlugin()
...
]
...
}
使用MyPlugin之后的打包效果: