编辑:下面附有最小可重现代码
我能够成功构建我们的旧代码库,但是当使用
node ui/dist/server
运行代码时,我收到错误:
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/user/code/node/myapp/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
at Object.@babel/runtime/helpers/interopRequireDefault (file:///Users/user/code/node/myapp/ui/dist/server/index.js:19088:1)
at __webpack_require__ (file:///Users/user/code/node/myapp/ui/dist/server/index.js:20072:40)
at file:///Users/user/code/node/myapp/ui/dist/server/index.js:20119:30
at ModuleJob.run (node:internal/modules/esm/module_job:234:25)
at ModuleLoader.import (node:internal/modules/esm/loader:473:24)
at asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:123:5)
我的 babelrc 是:
{
"presets": [
[
"@babel/preset-env", {
"targets": {
"esmodules": true
},
"modules": false
}
],
["@babel/preset-react", {
"runtime": "automatic"
}]
],
"sourceType": "unambiguous",
"plugins": [
"@babel/plugin-transform-runtime",
"@babel/plugin-transform-modules-commonjs",
"@babel/plugin-proposal-object-rest-spread",
"@babel/plugin-transform-destructuring",
"@babel/plugin-transform-parameters",
"transform-decorators-legacy",
"@babel/plugin-transform-class-properties",
"syntax-dynamic-import"
],
"env": {
"development": {
"plugins": [
"transform-react-jsx-self"
]
},
"production": {
"presets": [
"react-optimize"
]
},
"test": {
"plugins": [
// "transform-es2015-modules-commonjs",
"dynamic-import-node"
]
}
}
}
我尝试使用
@babel/plugin-transform-modules-commonjs
插件进行实验,但错误仍然存在。错误出现在构建文件中。
20119号线:
var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "@babel/runtime/helpers/interopRequireDefault");
19088号线:
module.exports = require("@babel/runtime/helpers/interopRequireDefault");
Package.json 片段:
"type: module"
"dependencies": {
"@babel/plugin-transform-react-jsx": "^7.25.2",
"@babel/runtime": "^7.25.0",
"babel-plugin-transform-react-jsx-self": "^6.22.0",
}
最小可重现代码: https://github.com/Exter-dg/minimalBabel
编辑: 我创建了一个最小的可重复示例,我只使用 moment.print() 打印今天的日期(在
server.js
中)。我使用了相同的 babel 配置和 webpack 配置。 babel-node
生成的 dist/server/index.js 文件正在按预期使用我的 coedebase 中的 import
语句。
但是,它还使用 __webpack_modules__
,它使用 require
来导入依赖项。这是导致错误的原因。看起来像是 babel/Webpack 中的配置错误
问题在于您的代码库被视为 ES 模块(由于 package.json 中的“type”:“module”字段),但 Webpack 正在生成 CommonJS 风格的 require 调用,这与 ES 不兼容模块语法。
您的 Webpack 正在生成 require 调用,您需要确保您的配置正确处理 ES 模块。你可以像这样修复它:
// webpack.config.js
module.exports = {
output: {
filename: 'bundle.js',
libraryTarget: 'module', // Use ES Module
},
experiments: {
outputModule: true, // This allows Webpack to output ESM
},
// Ensure target is modern
target: ['web', 'es2020'],
};