在TypeScript中使用命名空间分布在多个模块文件中 [英] Using namespace spread over multiple module files in TypeScript

查看:958
本文介绍了在TypeScript中使用命名空间分布在多个模块文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始研究大型打字稿项目。

I've started work on a large-scale typescript project.

从一开始,我就想保持我的文件有条理(这个项目将在很多开发人员之间分配,所以订单非常必要)。

Right from the outset, I want to keep my files organized (this project will be split between lots of developers so order is very necessary).

我一直在尝试使用模块/命名空间并将类拆分为每个文件的单独文件,其中包含一个包含命名空间的文件夹。

I have been attempting to use modules / namespaces and splitting classes out into separate files for each one, with a folder holding the namespace.

文件结构为:

app.ts
\Classes
---- \Animals
---- ---- Mammals.ts
---- ---- Reptiles.ts

然后尝试使用以下内容导入app.ts中该命名空间中的所有文件: import *来自./Classes/Animals的动物

I then attempt to import all files in that namespace in app.ts using something like: import * as Animals from "./Classes/Animals"

至于命名空间文件本身,我尝试过以下操作,但没有成功:

As for the namespace files themselves, I have tried the following, with no success:

namespace Animals {
    export class Mammals {
        constructor() {
        }
    }
}

以及:

module Animals {
    export class Reptiles {
        constructor() {
        }
    }
}

不幸的是,路径永远不会被识别(因为它指向文件夹而不是单个文件)。这甚至可能吗?将我的所有类都放在一个文件夹中的一个文件夹中,这将导致文件长达数千行,并且这个项目不可维护。

Unfortunately, the path is never recognized (as it points to a folder and not a single file). Is this even possible? Having all my classes from a single namespace in one file will result in files which are thousands of lines long and for this project that is not maintainable.

我也注意到了TypeScript 1.5支持 tsconfig.json - 但是,有手动将每个文件添加到地图是开发人员开始添加类时引入问题的一种可靠方法。

I have also noticed that TypeScript 1.5 has support for tsconfig.json - however, having to add each file manually to the map is a sure-fire way of introducing issues when developers start adding classes.

注意:我使用的是Visual Studio 2015,TypeScript 1.5 (我相信,不知道如何验证)。我也启用了ES6支持。

NOTE: I'm using Visual Studio 2015, TypeScript 1.5 (I believe, not sure how to verify). I also have ES6 support turned on.

推荐答案

使用重新导出创建一个外部模块,用于对来自其他模块的类型进行分组和公开:

Use re-exporting to create an external module that groups and exposes types from other modules:

// Classes/Animals.ts
export * from '.\Animals\Mammals';
export * from '.\Animals\Reptiles';

然后像往常一样从新模块中导入类型:

Then import the types from the new module as usual:

// app.ts
import * as Animals from '.\Classes\Animals'

let dog: Animals.Dog;
let snake: Animals.Snake;

// app.ts
import { Dog, Snake } from '.\Classes\Animals'

let dog: Dog;
let snake: Snake;

这篇关于在TypeScript中使用命名空间分布在多个模块文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆