javascript - typescript & TypeORM : Cannot use import statement outside a module

标签 javascript node.js typescript postgresql typeorm

我已经使用 TypeORM 建立了一个 Typescript 项目,但我在编译时遇到了一些问题。
我的包结构是这样的:

root
├── db
│   ├── migrations
│   │   ├── a_migration.ts
│   ├── connection
│   │   ├── config.ts <- ormconfig
│   │   ├── encrypt.ts
│   │   ├── index.ts <- creates the connection
├── src
│   ├── card
│   │   ├── entity.ts
├── package.json
├── tsconfig.json
我的 config.ts 是:

export = {
  type: 'postgres',
  host: POSTGRES_HOST,
  port: POSTGRES_PORT,
  username: POSTGRES_USER,
  password: POSTGRES_PASS,
  database: POSTGRES_DB,
  synchronize: true,
  logging: false,
  entities: ['**src/**/*entity.{ts,js}'],
  migrations: ['**/migrations/*.{ts,js}'],
  cli: {
    entitiesDir: 'src/entity',
    migrationsDir: 'db/migrations',
  },
  namingStrategy: new SnakeNamingStrategy(),
};
tsconfig.json:
{
  "compilerOptions": {
    "baseUrl": ".",
    "target": "es6",
    "module": "CommonJS",
    "allowJs": false,
    "esModuleInterop": true,
    "noImplicitAny": true,
    "resolveJsonModule": true,
    "outDir": "./build",
    "strict": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true
  },
  "include": ["./src/*", "./db/*"],
  "exclude": ["./**/__tests__/*", "./**/__functionaltests__/*"]
}
我尝试更换 **实体和迁移中的前缀为 path.join + __dirname但随后 typeorm 无法检测到迁移文件和实体。我知道这与解析代码在 build 下的路径有关。文件夹,但我不确定如何解决这个问题。
如果我这样生活,CLI 适用于执行应用程序的未编译代码 (ts),例如 nodemon但不适用于已编译的(js)之一。
我从编译的 js 中得到的错误是:SyntaxError: Cannot use import statement outside a module任何帮助表示赞赏,非常感谢!

最佳答案

你的实体和迁移应该被赋予 build 目录而不是 src 目录。
synchronize应该设置为假。
尝试更新您的config.ts如下所示:

export = {
  type: 'postgres',
  host: POSTGRES_HOST,
  port: POSTGRES_PORT,
  username: POSTGRES_USER,
  password: POSTGRES_PASS,
  database: POSTGRES_DB,
  synchronize: false,
  logging: false,
  entities: ['build/src/**/*entity.{ts,js}'],
  migrations: ['build/db/migrations/*.{ts,js}'],
  cli: {
    entitiesDir: 'src/entity',
    migrationsDir: 'db/migrations',
  },
  namingStrategy: new SnakeNamingStrategy(),
};
注意 entities 中的更改和 migrations特性。如果这不起作用,很可能是因为我指定的路径不在 build 中。目录。在这种情况下,请根据需要进行更改。
希望这对你有帮助!干杯🍻 !!!

关于javascript - typescript & TypeORM : Cannot use import statement outside a module,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67546054/

相关文章:

javascript - 如何在 Highcharts 中鼠标悬停时显示数据标签?

javascript - Angularjs ng-repeat 跨多个 trs

node.js - 使用 LUIS 和 Microsoft Bot Framework 识别产品编号的最佳方法

javascript - 在加载了 ngmap 的 map 上显示信息窗口

javascript - 在不删除 Angularjs 中的历史记录的情况下更改 URL

javascript - Papaparse/文件不起作用 - 输出乱码

angularjs - 来自重定向的快速 Passport 身份验证空白页

node.js - 如何设置服务器运行 Node.js?

javascript - typescript 函数返回 NaN 值但数字类型

angular - 找不到类型为 '[object Object]' 的不同支持对象 'object'。 NgFor 仅支持绑定(bind)到 Iterables,例如 Angular 8 中的数组