简体   繁体   中英

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 :

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.

Is it possible to define the module in TypeScript like this:

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.


How can I do this in Typescript?

What you've described basically exactly how external modules in TypeScript work.

For example:

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);

Compile with --module commonjs and run zoo.js in node.

Yes it is possible to use the true js syntax. You are receiving the error since you are using the import keyword which expects the imported file to use the export keyword. If you want the js exports.foo syntax you should use var instead of import. The following will compile/work just fine:

var module = require('module.ts')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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