[英]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.