注意:我最近偶然发现了typeorm-entitysharer,它“可用于基于相同的 TypeORM 实体创建客户端/服务器类,允许您共享它们。”它使您可以更好地控制要共享的内容,您可以查看他们的示例。我没有选择使用它,因为我猜这对我来说有点矫枉过正。但是,这就是我构建上一个项目的方式:
我将前端和后端放在一个存储库中,但是我想您可以将它们分开,但是您仍然需要以某种方式将它们彼此相邻。文件结构将是这样的:
workspace
├─backend <- repo #1
│ ├─src
│ │ ├─shared <- shared code goes here
│ │ └─proxy.ts
│ └─tsconfig.json
└─frontend <- repo #2
├─src
│ └─proxy.ts
└─tsconfig.json
那么在backend/tsconfig.json你介绍
{
...
"paths": {
"@shared/*": [ "src/shared/*" ],
}
}
在frontend/tsconfig.json你介绍
{
...
"paths": {
"@shared/*": [ "../backend/src/shared/*" ],
// if you're using TypeORM, this package has dummy decorators
"typeorm": [ "node_modules/typeorm/typeorm-model-shim.js" ]
// you can do the same for other packages, point them to dummy paths
// altirnatively you can route the shared imports through the proxy.ts
// and replace them in frontend/src/proxy.ts with dummy ones
}
}
也别忘了在你的前端npm i typeorm。
示例
假设我在backend/src/shared/user.entity.ts 有这个
import { PrimaryGeneratedColumn, Column } from 'typeorm';
export class UserEntity
{
@PrimaryGeneratedColumn() id: number;
@Column() name: string;
@Column() password: string;
}
现在,我可以像这样在任何地方使用它:
import { UserEntity } from '@shared/model/user.entity';
在后端,很明显,在前端,@shared/model/user.entity 被映射到 ../backend/src/shared/model/user.entity,而实体内部的 import from 'typeorm' 被映射到虚拟包。