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

使用sequelize-typescript创建Model文件后TS编译报错求助

解决sequelize-typescript在ES模块项目中加载模型时的ERR_REQUIRE_ESM错误

错误根源是sequelize-typescript内部使用了CommonJS的require()方法加载模型文件,但你的项目通过package.json的"type": "module"声明为ES模块环境,所有.ts文件被识别为ES模块,而require()不支持加载ES模块,因此触发冲突。即使你自己的代码全用import,ORM内部的require调用依然会报错。


方案1:修改Sequelize初始化配置,强制用动态import加载模型

在初始化Sequelize实例时,通过modelMatch选项替换默认的require加载逻辑,改用动态import()来加载模型文件,适配ES模块环境:

import { Sequelize } from 'sequelize-typescript';

const sequelize = new Sequelize({
  // 你的数据库基础配置
  dialect: 'mysql', // 替换为你使用的数据库类型(postgres/sqlite等)
  host: 'localhost',
  username: 'your-username',
  password: 'your-password',
  database: 'your-db-name',
  
  // 模型路径配置
  modelPaths: [__dirname + '/models'],
  
  // 关键:自定义模型匹配逻辑,用动态import替代require
  modelMatch: async (filename, member) => {
    // 从文件名提取模型名称(例如tweet.model.ts → tweet)
    const modelName = filename.slice(0, filename.indexOf('.model.ts'));
    // 动态导入模型文件
    const module = await import(`./models/${filename}`);
    // 返回匹配的模型成员
    return module[member];
  },
  
  // 可选:适配数据库dialect的ES模块配置
  dialectOptions: {
    supportBigNumbers: true,
    bigNumberStrings: true
  }
});

方案2:补充tsconfig.json的ES模块兼容配置

确保你的tsconfig.json包含以下关键配置,让TypeScript正确编译和解析ES模块:

{
  "compilerOptions": {
    "target": "ES6",
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "allowSyntheticDefaultImports": true, // 允许默认导入CommonJS模块
    "resolveJsonModule": true, // 支持导入JSON文件
    "rootDir": "./src",
    "sourceMap": true,
    "outDir": "./dist",
    "removeComments": true,
    "noEmitOnError": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "noUnusedLocals": true,
    "noImplicitReturns": true,
    "skipLibCheck": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules"]
}

方案3:更新依赖版本与启动命令

  • 确保ts-node和sequelize-typescript为最新版本,旧版本可能存在ES模块兼容bug:
    npm install ts-node@latest sequelize-typescript@latest
    
  • 启动命令保持使用ts-node-esm,添加--watch参数实现监听:
    ts-node-esm --watch ./src/server.ts
    

临时 workaround(不推荐长期使用)

如果以上方案暂时不生效,可以在src/models/目录下新建一个package.json,内容如下:

{
  "type": "commonjs"
}

这会让models目录下的文件被识别为CommonJS模块,避开require()加载ES模块的错误,但会破坏项目整体的ES模块一致性,仅作为临时调试使用。


内容的提问来源于stack exchange,提问作者wisie

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 16:03:20