You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用TypeScript+Sequelize时遭遇[ERR_REQUIRE_ESM]错误求助

Sequelize CLI 执行命令时遇到 ES Module 与 CommonJS 兼容问题

我在Docker容器内外执行任何需要读取config.mjs配置文件的Sequelize命令时,都会触发以下错误:

Error reading "build/database/config/config.js". Error: Error [ERR_REQUIRE_ESM]: require() of ES Module /backend/build/database/config/config.js from /backend/node_modules/sequelize-cli/lib/helpers/config-helper.js not supported. Instead change the require of config.js in /backend/node_modules/sequelize-cli/lib/helpers/config-helper.js to a dynamic import() which is available in all CommonJS modules.

尝试将config.mjs改为CommonJS格式(使用require)后,又引发连锁导入错误,比如models文件夹下的index.js报错:

File '/home/giovani/Projetos/GiovaniJogos/backend/src/database/config/config.ts' is not a module.

所有文件均已从TypeScript编译到build文件夹。我用.mjs而非.js是因为config.js无法被识别为ES模块;也曾在package.json中设置"type": "module",但问题依旧。

相关配置文件

config.mts(编译前)

import 'dotenv/config'
import { type Options } from 'sequelize'

const config: Options = {
  username: process.env.MYSQL_USER,
  password: process.env.MYSQL_PASSWORD,
  database: process.env.MYSQL_DATABASE,
  host: process.env.MYSQL_HOST,
  port: Number(process.env.MYSQL_PORT),
  dialect: 'mysql'
}

module.exports = config

index.ts

import { Sequelize } from 'sequelize'
import * as config from '../config/config.mjs'

export default new Sequelize(config)

tsconfig.json

{
  "compilerOptions": {
    "target": "ES6",
    "module": "ES6",
    "sourceMap": true,                     
    "outDir": "./build",
    "rootDir": "./src",
    "strict": true,
    "moduleResolution": "node",
    "baseUrl": ".",
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "strictPropertyInitialization": false,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "skipLibCheck": true,
    "paths": {
      "*": ["node_modules/*"]
    }
  },
  "include": ["src/**/*"],
}

依赖及Node版本

  • 依赖版本:
    "sequelize-cli": "^6.3.0",
    "ts-node": "^10.9.1",
    "ts-node-dev": "^2.0.0",
    "typescript": "^5.3.3",
    "sequelize": "^6.9.0",
    "mysql2": "^3.0.0"
    
  • Node版本:20.12.2

已尝试的解决方法

  • 修改tsconfig.json中target和module的多种组合
  • 移除tsconfig.json中的module属性
  • 在package.json中设置"type": "module"
  • 在config文件夹内添加仅含{"type": "commonjs"}的package.json
  • 参考Stack Overflow相关帖子的方案,但仍引发连锁错误

现在的困境是:要么遇到[ERR_REQUIRE_ESM]错误,要么不通过.mts扩展名或package.json配置转为模块时出现SyntaxError: Cannot use import statement outside a module错误。这套基础配置在3篇教程中都能正常运行,我实在找不到问题所在。

内容的提问来源于stack exchange,提问作者Giovani Souza Kill StevePlays

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 04:35:56