TypeError: CleanWebpackPlugin is not a constructor

引起错误的代码

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

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

执行npx webpack的时候出现下面的提示:

TypeError: CleanWebpackPlugin is not a constructor
at Object.<anonymous> (D:\webpack-demo\webpack.config.js:11:9)
    at Module._compile (D:\webpack-demo\node_modules\v8-compile-cache\v8-compile-cache.js:192:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)
...

原因分析

根据官方文档的解释,clean-webpack-plugin插件将会默认移除webpackoutput.path目录下的所有文件,以及每次构建之后所有未使用的webpack资源。如果你使用webpack版本高于4,那么意味着在/dist/目录下的所有文件会被默认清除,当然你可以使用cleanOnceBeforeBuildPatterns来重写这一行为。例如:

new CleanWebpackPlugin({
    // 默认: ['**/*'],cleanOnceBeforeBuildPatterns模式是相对于webpack的output.path。
    // 如果output.path之外使用绝对路径path.join(process.cwd(), 'build/**/*')
    // 需要首先运行dry: true来确保删除没有任何意外
    cleanOnceBeforeBuildPatterns: ['**/*', '!static-files*']
})

官方示例

const { CleanWebpackPlugin } = require('clean-webpack-plugin'); // installed via npm
const HtmlWebpackPlugin = require('html-webpack-plugin'); // installed via npm
const webpack = require('webpack'); // to access built-in plugins
const path = require('path');

module.exports = {
    entry: './path/to/my/entry/file.js',
    output: {
        /**
         * With zero configuration,
         *   clean-webpack-plugin will remove files inside the directory below
         */
        path: path.resolve(process.cwd(), 'dist'),
    },
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                loader: 'babel-loader',
            },
        ],
    },
    plugins: [
        new webpack.ProgressPlugin(),
        new CleanWebpackPlugin(),
        new HtmlWebpackPlugin({ template: './src/index.html' }),
    ],
};

所以错误的原因一在于导入语句书写有误,应该是:

// es modules
import { CleanWebpackPlugin} from 'clean-webpack-plugin';

// common js
const { CleanWebpackPlugin} = require('clean-webpack-plugin');

原因二在于CleanWebpackPlugin选项的参数传入错误,如果和默认删除目录不同时才需要传入路径,且需要通过选项cleanOnceBeforeBuildPatterns来传入。

参考文章

  1. clean-webpack-plugin

你可能感兴趣的:(webpack)