簡體   English   中英

是否可以在打字稿中使用nodejs樣式模塊?

[英]Is it possible to use nodejs style modules in typescript?

在node中,我可以通過設置exports對象的屬性來定義這樣的模塊:

module.js

exports.fun = function (val) {
    console.log(val);
};

並使用var module = require('module')進行詢問,並使用module.fun()函數。

是否可以像這樣在TypeScript中定義模塊:

module.ts

exports.fun = function (val :string) {
    console.log(val);
};

然后使用諸如語法之類的節點將模塊導入其他文件中,例如, import module = require('module.ts')以便編譯為nodejs,但是,如果現在我在某些.ts文件中使用module.fun() ,如果參數與module.ts文件中指定的類型不匹配,應該給我一個錯誤。


如何在Typescript中做到這一點?

您基本上已經描述了TypeScript中的外部模塊如何工作。

例如:

Animals.ts

export class Animal {
    constructor(public name: string) { }
}

export function somethingElse() { /* etc */ }

Zoo.ts

import a = require('./Animals');
var lion = new a.Animal('Lion'); // Typechecked
console.log(lion.name);

使用--module commonjs編譯,並在node中運行zoo.js。

是的,可以使用真正的js語法。 由於使用的import關鍵字期望導入的文件使用export關鍵字,因此您收到錯誤。 如果要使用exports.foo語法,則應使用var而不是import。 以下將編譯/工作正常:

var module = require('module.ts')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM