'How to expose any API globally on Node
I have a web development framework which I use on personal backend projects. All web apps revolve around my framework and the API is quite big so importing it in each file becomes tiring and repetitive.
The solution I came up with is using this code in my program main/entry point
Object.assign(global, require("@mycompany/myframework"));
Now I'm able to access all classes, constants and functions without importing them in each file.
The only problem is that my framework is written in TypeScript but my IDE is not recognising the types globally, so after using any of my framework class, the editor/IDE will report that the API has not been imported.
Do you have a complete solution for this problem?
Solution 1:[1]
For this you need a type declaration file like .d.ts
and inside that you should add something like below
declare module NodeJS {
interface Global {
myGlobalFunction: MyGlobalFunctionType
}
}
which helps you to create a module and disconnect it from the global type declaration namespace. Not sure if it helps you, but this is one of the way to handle such a situation.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nikhil Unni |
