Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

javascript - Using namespace spread over multiple module files in 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.

The file structure is:

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

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() {
        }
    }
}

and also:

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.

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.

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

question from:https://stackoverflow.com/questions/31983209/using-namespace-spread-over-multiple-module-files-in-typescript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

// Classes/Animals.ts
export * from '.AnimalsMammals';
export * from '.AnimalsReptiles';

Then import the types from the new module as usual:

// app.ts
import * as Animals from '.ClassesAnimals'

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

Or

// app.ts
import { Dog, Snake } from '.ClassesAnimals'

let dog: Dog;
let snake: Snake;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...