Typescript: set "node_modules" directory path
Asked Answered
N

3

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?

Nonconformance answered 21/1, 2019 at 13:32 Comment(2)
"Module resolution" in the offical TypeScript documentation might help: typescriptlang.org/docs/handbook/module-resolution.html, especially the section (w/ examples) "Path mapping"Floristic
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.Bentonbentonite
B
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.

Bentonbentonite answered 18/6, 2019 at 21:27 Comment(2)
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.Respective
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.Respective
K
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

Knapp answered 1/6, 2020 at 4:54 Comment(0)
A
1

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.

Ayr answered 5/1, 2023 at 1:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.