Loader 实现资源加载,Plugin 解决其他自动化工作。
常用插件
清除插件
clean-webpack-plugin 的作用是清除打包的目录。
// webpack.config.js
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
plugins: [
new CleanWebpackPlugin(),
]
HTML生成插件
html-webpack-plugin 的作用是打包生成 html 文件。这样 html 可以避免硬编码的资源路径。
// webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin')
plugins: [
// 用于生成 index.html
new HtmlWebpackPlugin({
title: 'Webpack Plugin Sample',
meta: {
viewport: 'width=device-width'
}, // 可以设置一些元素
template: './src/index.html' // 可以指定模板
}),
// 用于生成 about.html
new HtmlWebpackPlugin({
filename: 'about.html'
})
]
复制插件
copy-webpack-plugin 通常用于上线前将静态资源一起打包。
// webpack.config.js
const CopyWebpackPlugin = require('copy-webpack-plugin')
plugins: [
new CopyWebpackPlugin([
// 'public/**'
'public'
]), // 拷贝 public 目录下所有文件
new CopyWebpackPlugin({
patterns: [
{
from: { 'public' },
globOptions: {
ignore: ['**/index.html'] // 忽略 public 目录下的index.html
}
}
]
}), // 拷贝 public 目录下所有文件
]
开发一个插件
Plugin 实际上是通过钩子机制实现的。Plugin 应该是一个函数或者包含 apply 方法的对象。一般定义一个包含 apply 方法的类。
开发一个清除 “/*…/“这种不必要的注释的插件 MyPlugin。
// webpack.config.js
class MyPlugin {
apply(compiler) {
compiler.hooks.emit.tap('MyPlugin', compilation => {
// compilation => 可以理解为此次打包的上下文
for (const name in compilation.assets) {
// name => 文件名
// console.info(compilation.assets[name].source())
if (name.endsWith('.js')) {
const contents = compilation.assets[name].source() // 获取内容
const withoutComments = contents.replace(/\/\*\*+\*\//g, '') // 清除注释
// 写入处理后的内容
compilation.assets[name] = {
source: () => withoutComments, // 新内容
size: () => withoutComments.length // 新内容的大小
}
}
}
})
}
}
plugins: [
new MyPlugin(),
]