12

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?

2
  • "Module resolution" in the offical TypeScript documentation might help: typescriptlang.org/docs/handbook/module-resolution.html, especially the section (w/ examples) "Path mapping" Commented Jan 21, 2019 at 13:43
  • I'm having the same issue.. I'm using yarn workspaces which places the node_modules in different location. People using Lerna may also have this problem. Commented Jun 18, 2019 at 21:13

3 Answers 3

9

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I don't know if this has changed but now it says 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.
Actually that's talking about stuff like import "/path/to/react";. baseUrl does work but it should point to the actual node_modules directory, not the directory containing node_modules.
4

This is the way I solved this issue with Typescript within the root directory:

I set tsconfig.json to:

"compilerOptions": {

   "baseUrl": "./",

   "typeRoots": ["node_modules/@types"],
 }

I hope this helps someone to complement the previous answer.

RON

Comments

3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.