webpack报错“CleanWebpackPlugin is not a constructor”

2,249 阅读1分钟

clean-webpack-plugin 是一个比较普及的管理插件,在webpack中经常用到,它主要用于清理 /dist 文件夹。由于过去的指南和代码示例遗留下来,导致我们的 /dist 文件夹相当杂乱。webpack 会生成文件,然后将这些文件放置在 /dist 文件夹中,但是 webpack 无法追踪到哪些文件是实际在项目中用到的。 通常,在每次构建前清理 /dist文件夹,是比较推荐的做法,因此只会生成用到的文件。 首先,安装和配置

npm install clean-webpack-plugin --save-dev

webpack.config.js

 const path = require('path');
  const HtmlWebpackPlugin = require('html-webpack-plugin');
+ const CleanWebpackPlugin = require('clean-webpack-plugin');

  module.exports = {
    entry: {
      app: './src/index.js',
      print: './src/print.js'
    },
    plugins: [
+     new CleanWebpackPlugin(['dist']),
      new HtmlWebpackPlugin({
        title: 'Output Management'
      })
    ],
    output: {
      filename: '[name].bundle.js',
      path: path.resolve(__dirname, 'dist')
    }
  };

执行 npm run build,却发现报错

原来根据官方clean-webpack-plugin发现,

const { CleanWebpackPlugin } = require('clean-webpack-plugin');
 
const webpackConfig = {
    plugins: [
        /**
         * All files inside webpack's output.path directory will be removed once, but the
         * directory itself will not be. If using webpack 4+'s default configuration,
         * everything under <PROJECT_DIR>/dist/ will be removed.
         * Use cleanOnceBeforeBuildPatterns to override this behavior.
         *
         * During rebuilds, all webpack assets that are not used anymore
         * will be removed automatically.
         *
         * See `Options and Defaults` for information
         */
        new CleanWebpackPlugin(),
    ],
};
 
module.exports = webpackConfig;

如果webpack4以后的版本,就会报这个错误。好了,问题终于解决了!