ReferenceError: require 没有在 ES 模块作用域中定义

spa*_*ark 3 typescript webpack-5

我在 typescript 项目中添加了如下的 webpack 5 配置:

const path = require('path');
const webpack = require('webpack');

module.exports = {
  entry : {
    'index' : './index.ts', 
  } ,
  resolve: {
    extensions: ['.tsx', '.ts', '.js'],
    alias: {
        vue: 'vue/dist/vue.esm-bundler.js',
        '@': path.resolve(__dirname, '../../../src'),
    },
  },
  output : {
    path : path.resolve(__dirname, '../../bundle') ,
    filename : '[name].js'
  },
  module : {
    rules : [
      {
        test: /\.ts$/,
        loader: 'ts-loader',
        options: {
          appendTsSuffixTo: [/\.vue$/]
        },
        include: [
          path.resolve(__dirname, '../../../node_modules/js-wheel'),
          path.resolve(__dirname, '../../../src')
        ],
        exclude: /node_modules|\.d\.ts$/
      }
    ]
  }
};
Run Code Online (Sandbox Code Playgroud)

但是当我使用这个命令来构建项目时:

"build": "rm -rf dist && webpack --mode development --config src/config/webpack.config.js",
Run Code Online (Sandbox Code Playgroud)

显示错误:

[webpack-cli] ReferenceError: require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a '.js' file extension and '/Users/xxx/source/dwarf/frontend/js/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
Run Code Online (Sandbox Code Playgroud)

如何更改 webpack 配置以支持 ES6?我正在从谷歌搜索但没有找到任何线索。是否可以转换与 ES6 不兼容的 webpack 配置?

Dol*_*hin 5

该错误表明您在项目中使用了 ES 模块,但 require 是 CommonJS 导入方式,因此尝试使用 ES 模块导入方式,如下所示:

import webpack from 'webpack';
Run Code Online (Sandbox Code Playgroud)

并像这样导出:

export default {
  entry : {
    'index' : './index.ts', 
  } 
}
Run Code Online (Sandbox Code Playgroud)