hgp*_*ana 1 typeorm ts-node nestjs
我在 NestJS + TypeORM 中遇到一个奇怪的问题。
我几乎已经在实体中创建了一个 ManyToMany 关系,并且在该关系的拥有方,我添加了不带参数的 @JoinTable() 。
运行 Nest build 后,entity.js 文件添加了一个新的 import const browser_1 = require("typeorm/browser");,我发现它用于在编译的 JS 文件 => 中声明 JoinTable 选项browser_1.JoinTable()。
问题是,当使用 typeorm 生成新的迁移文件时,我不断收到以下错误:
import { __awaiter, __generator } from "tslib";
^^^^^^
SyntaxError: Cannot use import statement outside a module
at wrapSafe (internal/modules/cjs/loader.js:979:16)
at Module._compile (internal/modules/cjs/loader.js:1027:27)
at Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Object.require.extensions.<computed> [as .js] (C:\XXX\XXX\dev\XXX\pistis-api\node_modules\ts-node\src\index.ts:1045:43)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Module.require (internal/modules/cjs/loader.js:952:19)
at require (internal/modules/cjs/helpers.js:88:18)
at Object.<anonymous> (C:\XXX\XXX\dev\XXX\pistis-api\dist\modules\collaborator\entity\collaborator.entity.js:17:19)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
Run Code Online (Sandbox Code Playgroud)
追踪问题,它似乎与正在从以下位置导入的浏览器导入有关./node_modules/typeorm/browser/index.js
我使用 .env 来配置 typeorm,内容如下:
TYPEORM_CONNECTION=postgres
TYPEORM_HOST=localhost
TYPEORM_USERNAME=xxxxx
TYPEORM_PASSWORD=xxxxx
TYPEORM_DATABASE=xxxx
TYPEORM_PORT=5432
TYPEORM_SYNCHRONIZE=false
TYPEORM_LOGGING=true
TYPEORM_DROP_SCHEMA=false
TYPEORM_MIGRATIONS_RUN=true
TYPEORM_ENTITIES=dist/modules/**/entity/*.js
TYPEORM_ENTITIES_DIR=src/modules/**/entity
TYPEORM_MIGRATIONS=dist/migrations/*.js
TYPEORM_MIGRATIONS_DIR=src/migrations
TYPEORM_MIGRATIONS_TABLE_NAME='orm_migrations'
Run Code Online (Sandbox Code Playgroud)
在我引入 ManyToMany 关系和 JoinTable 之前,此配置一直有效。就 .tsconfig 而言,我有:
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"lib": [
"dom",
"es6",
"dom.iterable",
"esnext"
],
"allowJs": true,
"declaration": true,
"removeComments": true,
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": false,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noImplicitThis": true,
"alwaysStrict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true
},
"include": [
"src"
]
}
Run Code Online (Sandbox Code Playgroud)
任何帮助,将不胜感激。
提前致谢!
因此,在一个月没有接触这个项目之后,我决定重新启动它并重新审视它。几乎发现这是一个与我导入 JoinTable 选项的方式相关的新手问题。我非常信任 IDE 来完成导入,但这是我的错误。所以,总结一下:
我有:
import {JoinTable} from 'typeorm/browser';
当我应该:
import {JoinTable} from 'typeorm';
为了将来参考,这些导入错误也可能源自像这样的简单错误,而不是我们在 Stackoverflow 上发现的告诉我们检查 tsconfig.json 等的复杂错误。
谢谢 :)