简体   繁体   English

Typescript个项目之间共享接口

[英]Sharing interfaces between Typescript projects

I am developing two projects (an Angular client and a NestJS server) that at the end consume the same interfaces, let's say User, Product, etc..我正在开发两个项目(一个 Angular 客户端和一个 NestJS 服务器),它们最终使用相同的接口,比如用户、产品等。

I am looking for a way not to duplicate these interfaces files in both projects, but rather have a mutualised project hosting shared code and referenced by the server and the client projets that have their own building setup.我正在寻找一种不在两个项目中复制这些接口文件的方法,而是让一个共享项目托管共享代码并由服务器和具有自己的构建设置的客户端项目引用。

Would you have any hint?你有什么提示吗? Thanks !谢谢 !

establish a new "common" typescript library repository, home to all your system-wide interfaces and functionality.建立一个新的“通用”typescript 库存储库,它是所有系统范围接口和功能的所在地。 version and publish this common library to npm for easy access版本发布这个公用库到npm方便访问

then both the client and server projects should npm install mycommonlibrary那么客户端和服务器项目都应该npm install mycommonlibrary

during local development, you should use npm link to develop and debug the common library, client, and server, all together simultaneously本地开发时,使用npm link同时开发调试公共库、客户端、服务端

opinionated advice: following the above pattern, i've found the following strategy useful: write all your app's "buisness logic" in the common library, and your mocks and testing code too -- this is very flexible: you can take, for example, what is normally your serverside business logic, but then run it on the clientside, wired up mocks of the database, so that you can exercise most of your system isomorphically like that, it's pretty neato自以为是的建议:遵循上述模式,我发现以下策略很有用:在公共库中编写您应用程序的所有“业务逻辑”,以及您的模拟和测试代码——这非常灵活:例如,您可以,通常你的服务器端业务逻辑是什么,但是然后在客户端运行它连接数据库的模拟,这样你就可以像那样同构地运行你的大部分系统,它非常整洁

I've just read an article about this case, I think it's gonna help with your problem,我刚刚读了一篇关于这个案例的文章,我认为它会对你的问题有所帮助,

In that article, they'll combine Angular and NestJS and learn how to take advantage of code sharing in a Nx monorepo.... sharing made easy in full-stack app with NX, angular and nestjs在那篇文章中,他们将结合 Angular 和 NestJS 并学习如何利用 Nx monorepo 中的代码共享…… 使用 NX、angular 和 nestjs 在全栈应用程序中共享变得容易

If you are using a single repository for both projects: I would define the shared interface in the server and use import type in the client.如果您为两个项目使用单个存储库:我会在服务器中定义共享接口并在客户端中使用import type

And I would not share interfaces if it is not in a single repository.如果它不在单个存储库中,我也不会共享接口。

An alternative is to create a third project with all your common assets.另一种方法是使用所有公共资产创建第三个项目。 You can refer its *.d.ts from both projects.您可以从这两个项目中引用它的 *.d.ts。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM