我是 TypeScript 初学者,但我有 Java 开发经验,我想知道用 TypeScript 编写时推荐的文件结构是什么——尤其是涉及到模块时。
假设我有几个模块:ui.dashboard
, ui.models
, util.events
, 和 util.common
.
这些模块中的每一个都可能包含几个类。在 Java 中,我将具有以下文件结构(其中 <base>
是项目的基础包,例如 com.my.app):
src/<base>/ui/dashboard/<file per class>
src/<base>/ui/models/<file per class>
src/<base>/util/events/<file per class>
src/<base>/util/common/<file per class>`
另一方面,在 TypeScript 中我看到了两种主要的方法来完成同样的事情:
平面设计:
src/ui.dashboard.js
src/ui.models.js
src/util.events.js
src/util.common.js
这里每个文件都包含一个包含所有相关类的模块定义。这没问题,但文件会变得庞大且难以管理。
分层设计
在这个设计中,我会像在 Java 中一样组织文件,但由于 TypeScript(据我所知)不支持跨文件声明模块,我将不得不编写一个 gulp/grunt 任务来组合文件在构建时进入模块。
作为 Java 程序员,这看起来更优雅,但我失去了一些工具支持,因为模块直到构建时才真正定义,因此对编辑器/IDE 不可见。
推荐的工作方式是什么?
最佳答案
同时使用 :) ES6 支持命名导出和默认导出,因此可以根据需要使用这两种设计。
项目的整体结构应该按照你说的原因采用分层设计,但也应该根据需要采用扁平化模块。特别是对于将合并到其他代码库中的包。
例如:
src/ui/dashboard/Class1.ts
src/ui/dashboard/Class2.ts
src/ui.dashboard.ts
src/ui/dashboard/Class1.ts
文件看起来像:
export class Class1 {}
src/ui.dashboard.ts
文件看起来像:
import {Class1} from './ui/dashboard/Class1';
import {Class2} from './ui/dashboard/Class2';
export default {
Class1: Class1,
Class2: Class2,
randomFunction: () => {},
}
但是,当有疑问时回退到默认导出。
ECMAScript 6 favors the single/default export style, and gives the sweetest syntax to importing the default. Importing named exports can and even should be slightly less concise. https://esdiscuss.org/topic/moduleimport#content-0
关于TypeScript 推荐的带有模块的项目结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32501064/