当webpack 打包时的 filename 设置的是 固定的名称时,每次打包的时候,新的文件会覆盖原来的文件,这样就不用删除原来的 output 出来的文件夹
但是如果 filename = “[name].bundle.[hash:5].js” 这样的有占位符的文件名,每次生成的文件名是不一样的,也就不会去覆盖上次生成的文件,手动每次打包前,去先把 output的目录给删除掉就太麻烦了
这时我们可以使用 webpack提供的一个小插件 clean-webpack-plugin
用法:
安装 :npm install --save-dev clean-webpack-plugin
在webpack.config.js中配置
const CleanWebpackPlugin = require("clean-webpack-plugin");
module.exports={
entry:{
...
},
output:{
...
},
module:{
rules:[
...
]
},
plugins:[
new CleanWebpackPlugin(), // 这样就可以了,里面不需要加什么路径了
]
}
补充:如果在new CleanWebpackPlugin(’./dist’)里面加入路径,会报Error: clean-webpack-plugin only accepts an options object. 为什么会报这样的错误呢?
原因如下:
这是由于clean-webpack-plugin版本问题导致的,在2.0.0以上的版本中,对clean-webpack-plugin的使用有了一定的变化
具体如下:
1.在2.0.0版本以前,也就是1.x版本中,官方文档指示的配置是这样的
plugins: [
new CleanWebpackPlugin(paths [, {options}])
]
也就是大多数视频中提到的传入一个数组,指定要删除的目录,但在我们跟着做的过程中就会报标题中的那个错误
2.在2.x版本以后,官方对它的使用进行了修改
plugins: [
// See Options and Defaults
new CleanWebpackPlugin()
],
可以看到去掉了复杂的参数,直接new即可使用
当然里面仍然可以配置,但是只能传入一个对象配置,无法再在第一个参数传入数组指定删除目录,传入对象的方式如下:
new CleanWebpackPlugin({
// Simulate the removal of files
// default: false
dry: true,
// Write Logs to Console
// (Always enabled when dry is true)
//
// default: false
verbose: true,
// Automatically remove all unused webpack assets on rebuild
// default: true
cleanStaleWebpackAssets: false,
// Do not allow removal of current webpack assets
//
// default: true
protectWebpackAssets: false,
// **WARNING**
//
// Notes for the below options:
//
// They are unsafe...so test initially with dry: true.
//
// Relative to webpack's output.path directory.
// If outside of webpack's output.path directory,
// use full path. path.join(process.cwd(), 'build/**/*')
//
// These options extend del's pattern matching API.
// See https://github.com/sindresorhus/del#patterns
// for pattern matching documentation
// Removes files once prior to Webpack compilation
// Not included in rebuilds (watch mode)
//
// Use !negative patterns to exclude files
//
// default: ['**/*']
cleanOnceBeforeBuildPatterns: ['**/*', '!static-files*'],
cleanOnceBeforeBuildPatterns: [], // disables cleanOnceBeforeBuildPatterns
// Removes files after every build (including watch mode) that match this pattern.
// Used for files that are not created directly by Webpack.
//
// Use !negative patterns to exclude files
//
// default: disabled
cleanAfterEveryBuildPatterns: ['static*.*', '!static1.js'],
// Allow clean patterns outside of process.cwd()
//
// requires dry option to be explicitly set
//
// default: false
dangerouslyAllowCleanPatternsOutsideProject: true,
dry: true,
});
clean-webpack-plugin更详细的用法可以参考npm中对clean-webpack-plugin详细的介绍