You need to enable JavaScript to run this app. Node.js + TypeORM 种子数据执行时模块导入错误的解决方法
优惠活动
大模型
产品
解决方案
定价
更多

Node.js + TypeORM 种子数据执行时模块导入错误的解决方法

问题:使用@jorgebodega/typeorm-seeding执行种子数据时出现模块错误

我在使用@jorgebodega/typeorm-seeding执行种子数据时,运行以下命令:

typeorm-seeding \
  --dataSource 01-Source/Implementation/Elements/DataBase/TypeORM_DataSource.ts \
  seed 01-Source/Implementation/Elements/DataBase/Seeders/*.ts

出现错误:

[cause]: Error: Unable to open file: "D:\IntelliJ IDEA***\TypeORM_DataSource.ts". Cannot use import statement outside a module

这是ts-node常见错误,但我已经在package.json中添加"type": "module",问题仍未解决。另外,TypeORM的迁移命令运行完全正常:

typeorm-ts-node-esm migration:generate ./01-Source/Implementation/Elements/DataBase/Migrations/Initialization -d ./01-Source/Implementation/Elements/DataBase/TypeORM_DataSource.ts

原因分析思路

@jorgebodega/typeorm-seeding文档提供了.ts文件的使用示例,说明工具内置TypeScript支持,大概率依赖ts-node。export/import是TypeScript的基础场景,疑惑该工具是否应该负责将TS转译为适配当前模块类型的代码?

附录

TypeScript配置

理论上ts-node的设置可以解决模块类型问题,我的tsconfig.json配置如下:

{
  "compilerOptions": {
    "target": "ESNext",
    "module": "ESNext",
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "strict": true,
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "baseUrl": "./01-Source",
    "paths": {
      "@CommonSolution/*": [ "./CommonSolution/*"],
      /* ... */
    }
  },
  "ts-node": {
    "compilerOptions": {
      "module": "CommonJS"
    },
    "require": [
      "tsconfig-paths/register"
    ]
  }
}

docker-compose.yaml配置

version: "3.5"
services:
  Database:
    image: postgres
    container_name: Example-Local-Database
    ports:
      - "${DATABASE_PORT}:${DATABASE_PORT}"
    environment:
      - "POSTGRES_PASSWORD=${DATABASE_PASSWORD}"
    volumes:
      - DatabaseData:/var/lib/postgresql/data
  # ...
volumes:
  DatabaseData:
    name: Example-Local-DatabaseData
    driver: local

内容的提问来源于stack exchange,提问作者Takeshi Tokugawa YD

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 20:32:31