nodejs 中的 TypeScript 模块导入 [英] TypeScript module import in nodejs

查看:89
本文介绍了nodejs 中的 TypeScript 模块导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 typescript 在 nodejs 中导入模块的最佳实践是什么?我来自 c# 背景,所以我想做这样的事情

What is best practice for importing modules in nodejs with typescript? I come from c# background so I want to do something like this

MyClass.ts

module MyNamespace {
    export class MyClass {
    }
}

app.ts

// something like using MyNamespace
new MyNamespace.MyClass();

MyClass.ts

export class MyClass {
}

app.ts

import MyClass = module("MyClass")
new MyClass();

我知道我可以这样做并且它会起作用,但是我必须为每个类想两个名字

I know I can do this and it will work, but then I have to think up for two names for each class

import MyClass2 = module("MyClass")
new MyClass2.MyClass();

重点是将类分离到多个 .ts 文件(最好每个类一个文件).那么问题来了,这是怎么做到的?

Point is separating classes to multiple .ts files (preferably one file per class). So question is, how is this done?

推荐答案

这里有两个选择:

如果您坚持使用 CommonJS 或 AMD 模块,那么您将不得不按照您在问题中描述的方式使用外部模块.您是否使用模块来声明您自己的命名空间主要是一个品味问题.规避指定两个名称问题的唯一方法是创建一个为该类型命名的变量:

If you insist on using CommonJS or AMD modules, then you will have to use external modules just the way you described it in your question. Whether or not you use a module to declare your own namespace is mostly a matter of taste. The only way to circumvent the issue of specifying two names is to create a variable that aliases the type:

mymodule.ts

export module MyNamespace {
    export class MyClass {
    }
}

app.ts

import ns = require('mymodule');
var myclass = new ns.MyNamespace.MyClass();
var myclassalias = ns.MyNamespace.MyClass;
var myclass2 = new myclassalias();

您的另一个选择是使用内部模块,这些模块主要用于在内部构建代码.在编译时使用引用路径将内部模块引入范围.

Your other option is to use internal modules which are mostly used to structure your code internally. Internal modules are brought into scope at compile time using reference paths.

mymodule.ts

module MyNamespace {
    export class MyClass {
    }
}

app.ts

///<reference path='mymodule.ts'/>
var myclass = new MyNamespace.MyClass();

我认为您必须自己决定这两种方法中的哪一种更合适.

I think you'll have to decide for yourself which of those two approaches is more appropriate.

这篇关于nodejs 中的 TypeScript 模块导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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