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

运行sequelize-cli-ts种子文件报import语句模块错误如何解决

问题解决方法

错误原因是你的种子文件混用了ES模块import语法和CommonJSmodule.exports语法,且tsconfig未包含种子文件目录,导致TS未将import转换为CommonJS兼容的require语法,Node.js运行时无法识别。

具体修复步骤

  • 第一步:修改tsconfig.json的include配置,添加种子文件所在目录(默认是根目录下的seeders文件夹,可根据你的实际路径调整):
{
  "compilerOptions": {
      "module": "commonjs",
      "target": "es2019",
      "lib": [
          "dom",
          "es2019"
      ],
      "moduleResolution": "node",
      "outDir": "dist",
      "sourceMap": true,
      "esModuleInterop": true,
      "emitDecoratorMetadata": true,
      "experimentalDecorators": true,
      "allowSyntheticDefaultImports": true,
      "typeRoots": [
          "./types",
          "./node_modules/@types"
      ]
  },  
  "include": [
      "src/**/*",
      "seeders/**/*"
  ],
  "exclude": [
      "node_modules",
      ".vscode"
  ]
}
  • 第二步:统一种子文件的模块语法,优先适配你当前配置的CommonJS模块规范,将import改为require写法即可:
'use strict';
const { Player } = require("../../app/models/player");

module.exports = {
  up: async (queryInterface, Sequelize) => {
      return Player.bulkCreate(
        [
          { name: "Inbal", email: "inbal@test.co.il",phone: "1111" },
          { name: "Tal", email: "tal@test.co.il",phone: "2222" },
          { name: "Sivan", email: "sivan@test.co.il" ,phone: "3333"}
        ],
        { hooks: true, individualHooks: true, validate: true }
      );
  },

  down: async (queryInterface, Sequelize) => {
    await queryInterface.bulkDelete("players", null, {});
  }
};
  • 第三步:调整执行逻辑,两种可选方案:
    1. 先执行tsc命令将TS代码编译到dist目录,再运行npx sequelize-cli-ts db:seed:all,需要提前在根目录创建.sequelizerc配置文件,指定编译后的文件路径:
    const path = require('path');
    module.exports = {
      config: path.resolve('dist/config/config.js'),
      'models-path': path.resolve('dist/app/models'),
      'seeders-path': path.resolve('dist/seeders'),
      'migrations-path': path.resolve('dist/migrations')
    }
    
    1. 直接用ts-node实时编译执行,不需要提前编译:
    npx ts-node node_modules/sequelize-cli-ts/lib/sequelize db:seed:all
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 04:15:04