在TypeScript中的等效概念是模块。

huangapple go评论54阅读模式
英文:

Equivalent concept of Java package in TypeScript

问题

将Java代码转换为TypeScript。Java代码包含包(每个包都在自己的文件夹中)。通常,每个包中会有大约20个文件。这导致新的TypeScript代码包含数十个单独的文件导入。

在TypeScript中,减少导入数量的惯用方法是什么?

  • 每个目录保留一个单独的文件,其中包含包中的所有内容?
  • 继续保留许多单独的文件导入?
英文:

I'm porting Java code to TypeScript. The Java code contains packages (each in its own folder). Typically, there were "many" (around 20) files in each package. This causes new TypeScript code to contain tens of individual file imports.

What would be the idiomatic TypeScript approach to reduce the number of imports?

  • Have a single file per directory which includes everything in the package?
  • Keep having many single file imports?

答案1

得分: 1

The equivalent concept is Namespaces

export namespace Foo {
  export class Bar {}
}
// other file
export namespace Foo {
  export class Baz {}
}
// compiles roughly to
export const Foo = {
   Bar: class Bar{},
   Baz: class Baz{},
}

What you want, however, is probably making index.ts that reexports all the things from there:

// index.ts
export * from './bar.ts'
export { Baz } from './baz.ts'
// you don't need to reexport internals, leave them in their files

Then all your imports will be merged into a single one:

import { Bar, Baz } from 'foo'
// or
import * as Foo from 'foo'
Foo.Bar
英文:

The equivalent concept is Namespaces

export namespace Foo {
  export class Bar {}
}
// other file
export namespace Foo {
  export class Baz {}
}
// compiles roughly to
export const Foo = {
   Bar: class Bar{},
   Baz: class Baz{},
}

What you want hovewer is probably making index.ts that reexports all the things from there:

// index.ts
export * from './bar.ts'
export { Baz } from './baz.ts'
// you don't need do reexport internals, leave them in their files

Then all you imports will be merged into a single one:

import { Bar, Baz } from 'foo'
// or
import * as Foo from 'foo';
Foo.Bar

huangapple
  • 本文由 发表于 2023年6月26日 15:08:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76554288.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定