javascriptnode.jsubuntutypescriptdefinitelytyped

Is there a way to add type definition globally in TypeScript 2+?


I have a bunch of simple .ts files. NOT projects (i.e. standalone .ts scripts). They use some node.js functionality. TypeScript and node type definitions are installed via

npm install -g typescript
npm install -g @types/node

Problem: on windows I can run tsc foo.ts with no problems. It transpiles .ts to .js just fine. But on Ubuntu 16.04 it gives me error TS2304: Cannot find name 'require', error TS2304: Cannot find name 'process' and etc. Even if add /// <reference types="node" /> to the top of foo.ts or add --types node switch to tsc I get error TS2688: Cannot find type definition file for 'node'.

It looks like installing some types globally works fine in Windows but not on Ubuntu, so I'm assuming that this is not by design. So is there a way to install them globally? Or more precisely: to reference globally installed type definitions on Ubuntu?


Solution

  • I found the solution. I had to manually specify the typeRoots with the path leading to there npm installed global packages. Like so: tsc --typeRoots /usr/lib/node_modules/@types (you can get the path for your system via npm root -g).

    Still not sure why it looks them up without any special work on Windows and doesn't on Ubuntu. Can't tell if it's a bug and if it is then in which version.

    Edit:

    // Usage example
    npm install -g @types/node
    root=$(npm root -g)
    tsc --typeRoots $root/@types foo.ts