是否可以在打字稿中使用 nodejs 样式模块

Is it possible to use nodejs style modules in typescript?

本文关键字:nodejs 样式 模块 是否      更新时间:2023-09-26

在节点中,我可以通过设置exports对象的属性来定义这样的模块:

模块.js

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

并使用var module = require('module') in并使用module.fun()功能来请求它。

是否可以像这样在 TypeScript 中定义模块:

模块.ts

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

然后使用类似 Node 的语法将模块导入其他文件,例如import module = require('module.ts'),以便它编译为 nodeJS,但是,如果现在我在某个 .ts 文件中使用 module.fun(),如果参数与 module.ts 文件中指定的类型不匹配,它应该给我一个错误。


如何在打字稿中执行此操作?

是的,可以使用真正的js语法。您收到错误,因为您使用的是 import 关键字,该关键字期望导入的文件使用 export 关键字。 如果你想要 js exports.foo语法,你应该使用 var 而不是导入。以下内容将很好地编译/工作:

var module = require('module.ts')

你基本上描述了TypeScript中的外部模块是如何工作的。

例如:

动物网

export class Animal {
    constructor(public name: string) { }
}
export function somethingElse() { /* etc */ }

动物园

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

使用 --module commonjs 编译并在节点中运行 zoo.js。