如何使用 node.js 在 Typescript 中的多个文件中拆分我的模块 [英] How do I split my module across multiple files in Typescript with node.js

查看:36
本文介绍了如何使用 node.js 在 Typescript 中的多个文件中拆分我的模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于在编写 Typescript 时如何实际构建代码的信息似乎几乎不存在.

It seems that the information on how to actually structure code when writing Typescript is next to non-existent.

我想在 node.js 中创建一个服务器.它有像 socket.io 这样的外部依赖.服务器太大而无法将其全部放在一个文件中(正如我想象的大多数情况下是这种情况),所以我想我应该将其拆分.我希望将每个类放在一个单独的文件中,并且我希望能够在整个项目中使用它们而无需像

I want to make a server in node. It has external dependencies like socket.io. The server will be too big to put it all in one file (as I imagine is the case most of the time) so I figured I'd split it up. I want to have each class in a separate file and I want to be able to use them in the whole project without needing to do something crazy like

import vector = require("vector.ts");
var vec = new vector.Vector();

我该怎么做?到目前为止,我似乎在两条战线上进行斗争.当我让 tsc 实际编译时,节点会在运行时抱怨,但是当我修改代码以使节点可以工作时,它不会编译.

How do I do that? So far it seems that I'm fighting on two fronts. When I get tsc to actually compile, node complains on runtime, but when I modify the code so that node would work, it doesn't compile.

如果有人能花时间一步一步地完成这一步,我将不胜感激.

I'd appreciate if someone could take the time to go through this step by step.

推荐答案

实际上你可以(现在):

Actually you can (by now):

文件:class1.ts:

file: class1.ts:

export class Class1 {
  name: string;

  constructor(name: string){
      this.name = name;
  }
}

文件:class2.ts:

file: class2.ts:

export class Class2 {
    name: string;
}

整合模块文件:classes.ts:

consolidating module file: classes.ts:

export { Class1 } from "./class1";
export { Class2 } from "./class2";

消费文件:

import { Class1, Class2 } from "./classes";

let c1 = new Class1("Herbert");
let c2 = new Class2();

通过这种方式,您可以为每个文件创建一个类(或接口).在一个合并模块文件 (classes.ts) 中,您可以引用构成模块"的所有实体.

In this manner you can have one class (or interface) per file. In one consolidating module file (classes.ts) you then reference all entities that make up your "module".

现在您只需引用(导入)单个模块文件即可访问您的所有类.您仍然可以在文件之间进行巧妙的划分.

Now you only have to reference (import) on single module file to access all of your classes. You still have a neat compartmentalization between files.

希望这对仍在寻找的人有所帮助.

Hope this helps anyone still looking.

这篇关于如何使用 node.js 在 Typescript 中的多个文件中拆分我的模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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