其實 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文件夾。