简体   繁体   English

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

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

In node, I can define a module like this by setting the properties of exports object : 在node中,我可以通过设置exports对象的属性来定义这样的模块:

module.js module.js

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

and the ask for it using var module = require('module') in and the use the module.fun() function. 并使用var module = require('module')进行询问,并使用module.fun()函数。

Is it possible to define the module in TypeScript like this: 是否可以像这样在TypeScript中定义模块:

module.ts module.ts

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

and then import the module in some other file using node like syntax, say, import module = require('module.ts') so that it compiles to nodejs but, if now I use module.fun() in some .ts file, it should give me an error if the arguments don't match the type specified in module.ts file. 然后使用诸如语法之类的节点将模块导入其他文件中,例如, import module = require('module.ts')以便编译为nodejs,但是,如果现在我在某些.ts文件中使用module.fun() ,如果参数与module.ts文件中指定的类型不匹配,应该给我一个错误。


How can I do this in Typescript? 如何在Typescript中做到这一点?

What you've described basically exactly how external modules in TypeScript work. 您基本上已经描述了TypeScript中的外部模块如何工作。

For example: 例如:

Animals.ts Animals.ts

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

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

Zoo.ts Zoo.ts

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

Compile with --module commonjs and run zoo.js in node. 使用--module commonjs编译,并在node中运行zoo.js。

Yes it is possible to use the true js syntax. 是的,可以使用真正的js语法。 You are receiving the error since you are using the import keyword which expects the imported file to use the export keyword. 由于使用的import关键字期望导入的文件使用export关键字,因此您收到错误。 If you want the js exports.foo syntax you should use var instead of import. 如果要使用exports.foo语法,则应使用var而不是import。 The following will compile/work just fine: 以下将编译/工作正常:

var module = require('module.ts')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM