英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论