Reputation: 168
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. 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.
I have the following node project setup.
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
{
"compilerOptions": {
"target": "es6",
"module": "commonjs"
},
"exclude": [ ]
}
jsconfig.json
{
"compilerOptions": {
"target": "ES6"
}
}
Upvotes: 2
Views: 14947
Reputation: 79
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.
In your case just add an index.ts under /messages directory like this and remove declare module.
import * as M1 from "./M1";
import * as M2 from "./M2";
export {M1, M2};
Upvotes: 3
Reputation: 6059
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. 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:
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.
Here's the documentation on module resolution for TypeScript, it is a good one.
Upvotes: 1