简体   繁体   English

浏览器与服务器代码的打字稿编译时条件

[英]Typescript compile-time conditional for browser vs server code

I'm trying to share code between browser and server parts of a web app.我正在尝试在 Web 应用程序的浏览器和服务器部分之间共享代码。 It might be useful to have something like an #if conditional.拥有类似#if条件的东西可能会很有用。 Is there anything like that in Typescript?打字稿中有类似的东西吗?

For example:例如:

interface Card {
    id: Uuid
    text: string
    created_dt: Date
}

One the server, Uuid is a type from a database library.在服务器中, Uuid是数据库库中的一种类型。 On the browser I'll need to use something else.在浏览器上,我需要使用其他东西。

Hypothetical code:假设代码:

#if compiling_for_browser
type Uuid = somelib.Uuid
#else
type Uuid = database_lib.types.Uuid
#endif

interface Card ...

It appears that this is the most popular library implementing conditional compilation https://github.com/nippur72/ifdef-loader看来这是实现条件编译的最受欢迎的库https://github.com/nippur72/ifdef-loader

The TypeScript team has not implemented it and doesn't seem to be moving quickly to do so, for my use (same use case, basically) I'm going to try some of the webpack conditional compilation items so I can build easily for web and react-native TypeScript 团队还没有实现它,而且似乎也不会很快这样做,为了我的使用(基本上是相同的用例),我将尝试一些 webpack 条件编译项目,这样我就可以轻松地为 web 构建和本机反应

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

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