The NODE_PATH environment variable can be used to specify an alternative module folder. This can be useful for preventing long relative paths. Imagine the following folder structure:
/index.ts
/src/
---/folder1/
------/service.ts
---/folder2/
------/util.ts
If I want to use the service from folder1 in util from folder2 I need to do an import { ServiceName } from "../folder1/service"
. This can become tedious with deeply nested folders.
When you set the NODE_PATH environment variable to './src' you can import the same service from "folder1/service"
. As you can see, no annoying relative paths.
I have tested this with a plain javascript project and it works great. But when I use typescript it will give a compile error telling it can't find the specified modules because it doesn't seem to use NODE_PATH value.
So the question is, how do I force the typescript compiler to use the NODE_PATH value?
It's important to note that the two module names you've used there are fundamentally different: one is relative ("../folder1/service") while one is not ("folder1/service"). TypeScript treats relative and non-relative modules totally separately: take a look at module resolution in the docs for the full details.
One way to resolve this right now may well be to set your module resolution strategy to 'classic', which should mean that "folder1/service" gets searched for in the current directory (finding nothing), but then moves to the directory above (where it matches). This doesn't answer your question in general, as you can come up with other NODE_PATH options where it doesn't work, and it might break places where you're depending on 'node' style module resolution. In principle it will solve your specific issue though.
Otherwise, there isn't a 'right answer' for doing this well right now. Very very soon now though TypeScript 2.0 will land (planned for the end of June, last I heard, which is today), which includes path mapping and virtual root directories. These are config options you can add to you tsconfig.json, which allows you to arbitrarily map one path to another for module lookup. That should let you duplicate your NODE_PATH mapping into your compilation config, and everything should Just Work.
I know that doesn't solve your problem right now, sorry, but I expect it will solve it nicely within the next few weeks, once 2.0 is available.
This has been requested before : https://github.com/Microsoft/TypeScript/issues/8760 (you can follow along for updates there).
The suggestion is to use path mapping : https://github.com/Microsoft/TypeScript-Handbook/blob/release-2.0/pages/Module%20Resolution.md#path-mapping
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With