How to set paths property in a project with multiple tsconfig.json?
Asked Answered
B

3

25

I have the following file structure

|__ app1/
|   |__ tsconfig.json
|__ utilities/
|   |__ files.ts
|__ base-tsconfig.json

In base-tsconfig.json I have set the paths property as following

"compilerOptions": {
        "baseUrl": ".",
        "paths": {
            "utils/*": ["utilities/*"]
        }
}

and in tsconfig.json it looks as follow

{
    "extends": "../base-tsconfig",
}

That should be enough right? I am still getting below message though.

Cannot find module 'utils'

Breeding answered 29/6, 2018 at 9:52 Comment(2)
Did you find any solution yet?Plating
If you have any other paths in your inner tsconfig they will completely clobber the extended tsconfig, see github.com/Microsoft/TypeScript/issues/14527 (this is annoying as it breaks DRY)Bilinear
F
5

The problem is that paths resolution you've provided (utils/*) cannot resolve

import utils from `utils`

you should use

"paths": {
            "utils": ["utilities"]
        }

or if you need also scoped entries or sub-entries, like this:

// direct import from the `index.ts` barrel
// covered with `"utils": ["utilities"],`
import utils from `utils`

// import from a scoped entry (sub-entry):
// covered with `"utils/*": ["utilities/*"]`
// it will import it from `utilities/special.ts`
import utilsSpecial from `utils/special`
// or, it will import just `utilsSpecialAdd` exported symbol from the same `utilities/special.ts`
import { utilsSpecialAdd } from `utils/special`

you should cover both cases:

"paths": {
            "utils": ["utilities"],
            "utils/*": ["utilities/*"]
        }
Fostoria answered 4/10, 2020 at 19:34 Comment(2)
Could you give an example of a scoped entry or sub-entry?Paramorphism
Hi @PaulRazvanBerg, I added, I hope it is clear nowFostoria
C
1

The "paths" option can be used to inform the compiler of mappings but it does not perform these path transformations by itself. You can read more about this in the docs and in this issue. Most likely you are using a loader which does not allow remapping, such as Node.js's require().

There are packages available to help resolve this problem such as module-alias and tsconfig-paths.

Carthage answered 21/2, 2020 at 10:10 Comment(0)
V
0

The paths property should be set in the individual packages' tsconfig.json instead of base-tsconfig.json

// app1/tsconfig.json
{
  "extends": "../base-tsconfig.json",
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "utils/*": ["./utilities/*"]
    }
  }
}
Vivisection answered 27/3, 2022 at 0:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.