webpack 4.0 中 clean-webpack-plugin 的使用


其实 clean-webpack-plugin 很容易知道它的作用,就是来清除文件的。

一般这个插件是配合 webpack -p 这条命令来使用,就是说在为生产环境编译文件的时候,先把 build或dist (就是放生产环境用的文件) 目录里的文件先清除干净,再生成新的。

1. 为什么要用 clean-webpack-plugin

如果还不理解为什么要用它,就看看下面的例子就可以知道的。

webpack.config.js

const path = require('path')
...

module.exports = {
  entry: {
    "app.bundle": './src'
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].[chunkhash].js'
  },
  ...

};

在终端上运行:

$ npm run build
 
 

看看 dist 目录:

dist ├── app.bundle.e56abf8d6e5742c78c4b.js ├── index.html └── style.css 

你再把 src/index.js 改改内容,然后再执行 npm run build。 

再多运行几次,生成的带 hash 的 app.bundle.js 文件就会很多。

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 发挥的作用。

2. 使用 clean-webpack-plugin

首先来安装。

$ 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文件夹。

 

转载:https://www.jianshu.com/p/f4a209d58c35


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM