简体   繁体   English

Typescript:如何在节点中使用“声明模块”

[英]Typescript : How do I use “declare module” in node

How do i get declare module to work in Node, I get the typescript to compile without errors and the Intellisense in VS.Code works. 我如何使声明模块在Node中工作,如何使打字稿进行编译而没有错误,并且VS.Code中的Intellisense可以工作。 But i get "Cannot find module 'messages'" in runtime. 但是我在运行时得到“找不到模块'消息'”。

Clarification : I´m trying to get both the api.ts and mq.ts classes under the same "namespace" messages. 澄清:我试图将api.ts和mq.ts类都放在相同的“命名空间”消息下。

I have the following node project setup. 我有以下节点项目设置。

  • /messages/api.ts /messages/api.ts
  • /messages/mq.ts /messages/mq.ts
  • /main.ts /main.ts

api.ts api.ts

declare module "messages" {
export class Put {

    }
}

mq.ts 平方米

declare module "messages"{
export class GetWork {

    }
}

main.ts 主要

import * as messages from "messages";
let x = new messages.GetWork();

tsconfig.json tsconfig.json

{
   "compilerOptions": {
      "target": "es6",
      "module": "commonjs"
   },
   "exclude": [  ]
}

jsconfig.json jsconfig.json

{
   "compilerOptions": {
       "target": "ES6"
   }
}

In node you don't need to use declare module, every file is just a module, declare module is for d.ts and other usage. 在节点中,您不需要使用声明模块,每个文件都只是一个模块,声明模块用于d.ts和其他用途。

In your case just add an index.ts under /messages directory like this and remove declare module. 在您的情况下,只需在/ messages目录下添加一个index.ts并删除声明模块。

import * as M1 form "./M1";
import * as M2 form "./M2";

export {M1, M2};

A few things here, because you're trying to import messages without a relative path, with just the names, what TypeScript tries to do is to find a module in a node_modules folder. 这里有几件事,因为您试图导入的消息没有名称的相对路径,而只是名称,所以TypeScript试图做的是在node_modules文件夹中找到一个模块。 That's why it can't find any. 这就是为什么它找不到任何东西的原因。

So, if you want to import one of your own modules you should use a relative path. 因此,如果要导入自己的模块之一,则应使用相对路径。

Now, every file is a module. 现在,每个文件都是一个模块。 So if you have a file called mq.ts you should import it as follows: 因此,如果您有一个名为mq.ts的文件,则应按以下步骤导入它:

import { Put } from './mq';

The syntax: 语法:

declare module "messages" {
  // ....
}

is used only when creating Typings for existing node_modules and usually one would create a .d.ts file to do so. 仅在为现有的node_modules创建Typings时使用,并且通常会创建一个.d.ts文件来这样做。

Here's the documentation on module resolution for TypeScript, it is a good one . 这是有关TypeScript模块解析的文档,它是一个很好的文档

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

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