Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
605 views
in Technique[技术] by (71.8m points)

node.js - Correct way to reference modules from other modules in Typescript

I'm writing a module for NodeJS in Typescript. I'm trying to process a request (which should be an IncomingMessage object) using this module.

/// <reference path="typings/node/node.d.ts"/>
module rateLimiter {
  export function processRequest(req : http.IncomingMessage) : Boolean {
    return false;
  };
}

When attempting to ensure that the incoming request parameter req is such an instance, I find that I cannot reference anything from the http module. I think to myself "okay, so I need to import it because that's just an alias". When I do so however, I receive "import delcarations in a namespace cannot reference a module."

/// <reference path="typings/node/node.d.ts"/>
module rateLimiter {
  import http = require('http');//IMPORT DECLARATIONS IN A NAMESPACE CANNOT REFERENCE A MODULE
  export function processRequest(req : http.IncomingMessage) : Boolean {
    return false;
  };
}

So I try what seems like a poor decision, importing in the global scope, only to receive "cannot compile modules unless --module flag is provided"

/// <reference path="typings/node/node.d.ts"/>
  import http = require('http');//CANNOT COMPILE MODULES UNLESS --MODULE FLAG IS PROVIDED
module rateLimiter {
  export function processRequest(req : http.IncomingMessage) : Boolean {
    return false;
  };
}

I feel like I'm fundamentally missing how this sort of reference is supposed to be made. It feels like I shouldn't have to import a module just to use the definitions included in node.d.ts. Could someone shed some light on this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you are writing a module, nothing you write is in the global scope - the file itself is a module, and everything inside it is scoped to that module.

import http = require('http');

export function processRequest(req : http.IncomingMessage) : boolean {
    return false;
};

In the example above, the file, rateLimiter.ts is the module. http is imported into the rateLimiter module.

You need to compile with the module flag - for example:

tsc --module commonjs rateLimiter.ts

Most editors and IDEs supply a way to set this too.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...