Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use global Node packages with Typescript

Tags:

typescript

Using global packages is possible by install them via npm install -g ....
If Typescript types are installed in this way, they are also available in the global folder, for example /usr/lib/node_modules on a linux system.

When transpiling a typescript source file with tsc, a compiler error is printed out and the transpilation fails.

src/main.ts(3,26): error TS2307: Cannot find module 'express'.

However, I would expect that either environmental variables like NODE_PATH or configuration settings in file tsconfig.json like

{
    "compilerOptions": {
        ...
        "typeRoots": [
             "/usr/lib/node_modules/@types"
        ]
     }
}

could solve that problem (see also Typescript Documentation).

But all these settings are ignored. Only installing types locally in the project helps.

So my question, why are the settings in tsconfig.json ignored and are there any possibilities to use globally installed types packages

Example project:

After npm install you can run this project with npm start if all other dependencies are installed globally. Only 7 packages are installed with:

"devDependencies": {
    "@types/express": "^4.0.38",
    "@types/node": "^8.0.31",
    "@types/sprintf-js": "^1.1.0"
 }

If I remove the local directory node_modules you get the errors

src/main.ts(2,25): error TS2307: Cannot find module 'sprintf-js'.
src/main.ts(3,26): error TS2307: Cannot find module 'express'.

... although these packages are available in the global package folder /usr/lib/node_modules.

like image 345
Manfred Steiner Avatar asked Apr 30 '26 13:04

Manfred Steiner


1 Answers

Had the same issue as described above and for me the path property worked. Note that this is relative to basePath as described here. See the example below:

      "baseUrl": "/Users/myUser/Projects/myProject",
        "paths": {
            "bignumber.js": [
                "../../.nvm/versions/node/v16.15.1/lib/node_modules/bignumber.js"
            ],
            "moment": [
                "../../.nvm/versions/node/v16.15.1/lib/node_modules/moment"
            ],
            ]
        },
like image 116
Frank Essenberger Avatar answered May 04 '26 16:05

Frank Essenberger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!