typescript | 命名空间与导包,编译器链接多文件reference | ts-node使用

多文件导包,类似C#首先定义命名空间,在main文件中,使用import导入(using)命名空间。

这里需要注意的是,需要给编译器配置链接信息,即include操作。

例如:

定义命名空间Factory,导出一个函数create

// Factory.ts

namespace Factory {
  export function create<T>(c: { new (): T }): T {
    return new c()
  }
}

在另一个文件使用

index.ts

/// <reference path="Factory.ts" />
import create = Factory.create

class Hello {
  private mess: string = 'hello template'
  public show() {
    console.log(this.mess)
  }
}

function main() {
  let hello = create(Hello)
  hello.show()
}
main()

首先添加链接信息:/// <reference path="Factory.ts" />

导包: import create = Factory.create

编译项目 : tsc index.ts

————————————————————————

有一个不需要编译即可运行的工具ts-node,但是经测试它不能处理reference链接信息

它只能处理es6规范的导包

例如

// Factory.ts

export function create<T>(c: { new (): T }): T {
  return new c()
}

index.ts

import { create } from './Factory'

class Hello {
  private mess: string = 'hello template'
  public show() {
    console.log(this.mess)
  }
}

function main() {
  let hello = create(Hello)
  hello.show()
}
main()

运行: ts-node index.ts

猜你喜欢

转载自blog.csdn.net/u011607490/article/details/84700306