TypeError: webpack.optimize.UglifyJsPlugin不是一个构造函数

9

我遇到了一个 TypeError,不确定该如何解决。期待您能够提供帮助。以下是从 yarn run build 输出的终端内容:

BUILD_DIR /Users/blakelucey/Desktop/fsd-next/build
SRC_DIR /Users/blakelucey/Desktop/fsd-next/src
[webpack-cli] TypeError: webpack.optimize.UglifyJsPlugin is not a constructor
    at module.exports (/Users/blakelucey/Desktop/fsd-next/webpack.config.js:118:7)
    at WebpackCLI.loadConfig (/Users/blakelucey/Desktop/fsd-next/node_modules/webpack-cli/lib/webpack-cli.js:1589:33)
    at async WebpackCLI.resolveConfig (/Users/blakelucey/Desktop/fsd-next/node_modules/webpack-cli/lib/webpack-cli.js:1677:38)
    at async WebpackCLI.createCompiler (/Users/blakelucey/Desktop/fsd-next/node_modules/webpack-cli/lib/webpack-cli.js:2085:22)
    at async WebpackCLI.runWebpack (/Users/blakelucey/Desktop/fsd-next/node_modules/webpack-cli/lib/webpack-cli.js:2213:20)
    at async Command.<anonymous> (/Users/blakelucey/Desktop/fsd-next/node_modules/webpack-cli/lib/webpack-cli.js:850:25)
    at async Promise.all (index 1)
    at async Command.<anonymous> (/Users/blakelucey/Desktop/fsd-next/node_modules/webpack-cli/lib/webpack-cli.js:1516:13)
error Command failed with exit code 2.

这是 webpack.config.js 文件:
const webpack = require('webpack');
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
// const UglifyJsPlugin = require('uglifyjs-webpack-plugin');

const extractCSS = new ExtractTextPlugin('[name].fonts.css');
const extractSCSS = new ExtractTextPlugin('[name].styles.css');
// const MiniCssExtractPlugin = require("mini-css-extract-plugin");

const BUILD_DIR = path.resolve(__dirname, 'build');
const SRC_DIR = path.resolve(__dirname, 'src');

console.log('BUILD_DIR', BUILD_DIR);
console.log('SRC_DIR', SRC_DIR);

module.exports = (env = {}) => {
  return {
    entry: {
      index: [SRC_DIR + '/index.tsx']
    },
    output: {
      path: BUILD_DIR,
      filename: '[name].bundle.js'
    },
    node: {
      fs: "empty"
    },
    resolve: {
      extensions: ['.ts', '.tsx', '.js', '.jsx', '.css', 'scss']
    },
    // watch: true,
    devtool: env.prod ? 'source-map' : 'cheap-module-eval-source-map',
    devServer: {
      contentBase: BUILD_DIR,
      //   port: 9001,
      compress: true,
      hot: true,
      open: true
    },
    // optimization: {
    //   minimizer: [
    //     new UglifyJsPlugin({sourceMap: true})
    //   ]
    // },
    module: {
      rules: [
        {
          test: /\.tsx?$/,
          use: [
            {
              loader: 'ts-loader'
            }
          ],
        },
        {
          test: /\.(js|jsx)$/,
          exclude: /node_modules/,
          use: {
            loader: 'babel-loader',
            options: {
              cacheDirectory: true,
              presets: ['react', 'env']
            }
          }
        },
        {
          test: /\.html$/,
          loader: 'html-loader'
        },
        {
          test: /\.(scss)$/,
          use: ['css-hot-loader'].concat(extractSCSS.extract({
            fallback: 'style-loader',
            use: [
              {
                loader: 'css-loader',
                options: { alias: { '../img': '../public/img' } }
              },
              {
                loader: 'sass-loader'
              }
            ]
          }))
          // loader: MiniCssExtractPlugin.loader
        },
        {
          test: /\.css$/,
          use: extractCSS.extract({
            fallback: 'style-loader',
            use: 'css-loader'
          })
          // loader: MiniCssExtractPlugin.loader
        },
        {
          test: /\.(png|jpg|jpeg|gif|ico)$/,
          use: [
            {
              // loader: 'url-loader'
              loader: 'file-loader',
              options: {
                name: './img/[name].[hash].[ext]'
              }
            }
          ]
        },
        {
          test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
          loader: 'file-loader',
          options: {
            name: './fonts/[name].[hash].[ext]'
          }
        }]
    },
    plugins: [
      new webpack.HotModuleReplacementPlugin(),
      new webpack.optimize.UglifyJsPlugin({ sourceMap: true }),
      new webpack.NamedModulesPlugin(),
      extractCSS,
      extractSCSS,
      // new MiniCssExtractPlugin({
      //   // Options similar to the same options in webpackOptions.output
      //   // both options are optional
      //   filename: "[name].css",
      //   chunkFilename: "[id].css"
      // }),
      new HtmlWebpackPlugin(
        {
          inject: true,
          template: './public/index.html'
        }
      ),
      new CopyWebpackPlugin([
        { from: './public/img', to: 'img' }
      ],
        { copyUnmodified: false }
      ),
      new CopyWebpackPlugin([
        { from: './public/robot.txt', to: 'robot.txt' }
      ],
        { copyUnmodified: false }
      )
    ]
  }
};

我认为我需要删除这里的评论:

// const UglifyJsPlugin = require('uglifyjs-webpack-plugin');

并且在这里:

// optimization: {
    //   minimizer: [
    //     new UglifyJsPlugin({sourceMap: true})
    //   ]
    // },

但我并不确定。期待并感谢您的任何贡献,谢谢。

2个回答

14

您可能已经注意到插件uglifyjs-webpack-plugin已经被弃用,而terser-webpack-plugin作为替代方案推出。因此,在webpack.optimize中,UglifyJsPlugin插件可能无法使用。以下是修复问题的一种可能方法:

  • 只需在配置文件中删除以下行:
new webpack.optimize.UglifyJsPlugin({ sourceMap: true })
// Remove this ^
  • 并将插件添加到optimizer中:
const TerserPlugin = require("terser-webpack-plugin");

module.exports = {
  // ...
  optimization: {
    minimize: true,
    minimizer: [new TerserPlugin()],
  },
  // ...
};

关于NamedModulesPlugin is not a constructor,它也已经被弃用了,如果你正在使用webpack 5,可以在这里找到更多信息(链接)。基本上你可以删除该插件并将其替换为优化选项:

module.exports = {
  //...
  // NamedModulesPlugin → optimization.moduleIds: 'named'
  optimization: {
    moduleIds: 'named',
  },
};


这解决了上面的错误,但是我得到了一个新的错误:webpack-cli] TypeError: webpack.NamedModulesPlugin不是一个构造函数。你有什么建议可以帮我解决吗?谢谢。 - Blake Lucey
刚刚更新了关于您问题的答案。 - tmhao2005

0

我在互联网上搜索到了类似以下问题的内容,但无法解决我的项目问题

[https://dev59.com/C1YO5IYBdhLWcg3wF9sg][1]


请不要将评论发布为答案,@reza。 - Tiago Rangel de Sousa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接