其实 clean-webpack-plugin 很容易知道它的做用,就是来清除文件的。css
通常这个插件是配合 webpack -p
这条命令来使用,就是说在为生产环境编译文件的时候,先把 build或dist
(就是放生产环境用的文件) 目录里的文件先清除干净,再生成新的。html
若是还不理解为何要用它,就看看下面的例子就能够知道的。webpack
webpack.config.jsgit
const path = require('path') ... module.exports = { entry: { "app.bundle": './src' }, output: { path: path.resolve(__dirname, 'dist'), filename: '[name].[chunkhash].js' }, ... };
在终端上运行:github
$ npm run build
看看 dist
目录:web
dist ├── app.bundle.e56abf8d6e5742c78c4b.js ├── index.html └── style.css
你再把 src/index.js
改改内容,而后再执行 npm run build
。 npm
再多运行几回,生成的带 hash 的 app.bundle.js
文件就会不少。ruby
dist ├── app.bundle.0e380cea371d050137cd.js ├── app.bundle.259c34c1603489ef3572.js ├── app.bundle.e56abf8d6e5742c78c4b.js ├── index.html └── style.css
这些带 hash 的 app.bundle.js
只有最新的才有用,其余的都没用,咱们要在 build 以前把它们全清空,这真是 clean-webpack-plugin 发挥的做用。app
首先来安装。ui
$ npm i clean-webpack-plugin --save-dev
webpack.config.js
plugins:[ new CleanWebpackPlugin(), new HtmlWebpackPlugin({ template:'./src/index.html' }) ]
如今运行 npm run build
试试
注意的是:在最新版的webpack中 new CleanWebpackPlugin();中不须要写里面的目标路径,会自动清除生成的文件夹,好比是build文件夹。