How can i set/configure a resolution path for the whole "node_modules" directory (not separate modules) for Typescript compiler if that directory is not located in the default resolution path?
3 Answers
You may change where TypeScript looks for the node_modules folder as described here: https://www.typescriptlang.org/docs/handbook/module-resolution.html
Setting baseUrl informs the compiler where to find modules. All module imports with non-relative names are assumed to be relative to the baseUrl.
Add the following to your tsconfig.json file:
"compilerOptions": {
"baseUrl": "<dir_containing_node_modules>"
}
Sadly it looks like you cannot specify a different name for the node_modules folder - although this is a less likely situation. Please correct me if I'm wrong.
2 Comments
Lets you set a base directory to resolve *non-absolute* module names, so this doesn't let you affect e.g. how import "react"; works.import "/path/to/react";. baseUrl does work but it should point to the actual node_modules directory, not the directory containing node_modules.The solutions using baseUrl only work if your source code exists within that directory (if it doesn't, TS throws an error). If your source code is not nested under that folder, you can instead achieve this like so:
"compilerOptions": {
"baseUrl": ".",
"paths": {
"*": [ "absolute/or/relative/path/to/node_modules/*" ],
}
}
Please be aware that this is an exceptionally strange use case and isn't for the day-to-day building of applications. In my case, we have a code generator that I'm writing a smoke test for (does the output compile?), and I want it to pull its node_modules from a pre-existing location rather than having to install a new set of dependencies in the temp folder that the test is generating into.
node_modulesin different location. People using Lerna may also have this problem.