:::success 插件的使用以 npm 文档为准,部分插件经常更新,使用时如果发生错误可以参考 npm 文档 或者 webpack插件文档。 :::
1. clean-webpack-plugin
作用
该插件可以用于自动清除 dist 目录后重新生成,在使用 npm run build
时非常方便。
安装
npm i clean-webpack-plugin -D
配置
在 webpack.config.js 文件的 plugins 中创建。
注意 clean-webpack-plugin的 3.0 版本后,引入方式不同如下 :
const HtmlWebpackPlugin = require('html-webpack-plugin')
const {CleanWebpackPlugin} = require('clean-webpack-plugin') // 新的引入方式
//...
plugins: [
// 配置 html-webpack-plugin
new HtmlWebpackPlugin({
filename: 'index.html', // 在内存中生成的文件名
template: './src/index.html' // 模板,以磁盘上的这个文件为模板,不用引入 bundle.js
}),
// 配置 clean-webpack-plugin
new CleanWebpackPlugin()
],
copy-webpack-plugin
安装
npm i copy-webpack-plugin -D
配置
在 webpack.config.js 中的 plugins 中配置。
- from:源,从哪里拷贝,可以是相对路径或绝对路径,推荐绝对路径
- to:目标,拷贝到哪里去,相对于
output
的路径,同样可以相对路径或绝对路径,但更推荐相对路径。 ```javascript const HtmlWebpackPlugin = require(‘html-webpack-plugin’) const {CleanWebpackPlugin} = require(‘clean-webpack-plugin’) const CopyWebpackPlugin = require(‘copy-webpack-plugin’)
plugins: [ // 配置 html-webpack-plugin new HtmlWebpackPlugin({ filename: ‘index.html’, // 在内存中生成的文件名 template: ‘./src/index.html’ // 模板,以磁盘上的这个文件为模板,不用引入 bundle.js }), // 配置 clean-webpack-plugin new CleanWebpackPlugin(), new CopyWebpackPlugin([ { from: path.join(__dirname, ‘assets’), to: ‘assets’ } ]) ],
<a name="5hl6c"></a>
## 项目结构
project dir |_dist |_assets // <= 静态资源,比如图片 |-src |_index.html |_index.js |_css |_js |_static |_package.json
<a name="kEr1G"></a>
# BannerPlugin
这是一个 webpack 的内置插件,用于给打包的 JS 文件加上版权注释信息。
<a name="JuYjp"></a>
## 引入 webpack 内置插件
```javascript
const webpack = require('webpack')
使用
const webpack = require('webpack')
// ...
plugins: [
// 配置 html-webpack-plugin
new HtmlWebpackPlugin({
filename: 'index.html', // 在内存中生成的文件名
template: './src/index.html' // 模板,以磁盘上的这个文件为模板,不用引入 bundle.js
}),
// 配置 clean-webpack-plugin
new CleanWebpackPlugin(),
new CopyWebpackPlugin([
{
from: path.join(__dirname, 'assets'),
to: 'assets'
}
]),
// 使用 bannerPlugin , webpakc 的内置插件
new webpack.BannerPlugin('MangoLee!')
],