Monorepo with paths from Typescript is not working
Asked Answered
M

2

25

I have monorepo (yarn workpaces) with following file structure:

├── client                (workspace @client)
│   ├── package.json
│   └── tsconfig.json     (extended tsconfig)
├── server                (workspace @server)
│   ├── getData.ts
│   ├── package.json
│   └── tsconfig.json     (extended tsconfig)
├── shared
│   └── sanitizeData.ts
├── package.json          (monorepo root)
└── tsconfig.json         (base tsconfig)

And I want to use function from shared/sanitizeData.ts in server/getData.ts

I tried to use paths from Typescript, it looks pretty straightforward according to docs, but I'm doing something wrong:

error TS2307: Cannot find module '@shared/sanitizeData'.

server/tsconfig.json:

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "baseUrl": ".",
    "rootDir": "../",
    "outDir": "build",
    "paths": {
      "@shared/*": ["shared/*"]
    }
  }
}

server/getData.js:

import { sanitizeData } from "@shared/sanitizeData";

Could you help me please?

Meloniemelony answered 25/10, 2019 at 8:18 Comment(0)
R
8

Paths are relative to baseUrl, so in your case you'd have to replace ["shared/*"] with ["../shared/*"]

Reg answered 16/1, 2020 at 11:6 Comment(1)
This answer is correct, but one should also keep in mind that paths are overwritten - they are not merged! Adding the possibility to merge arrays in tsconfig.json is being discused in this GitHub issue.Philippa
M
5

Define the baseUrl only in the root tsconfig file, to prevent rebasing complexities. Then, references all paths from baseurl.

Remember: The paths property does not merge entries from multiple tsconfig files... as the "extends" argument implies. Paths of a base tsconfig get overwritten by the paths in the derived tsconfig.

So, you'll have to copy/move the paths from the base tsconfig to any derived tsconfig files.

And, be sure to decorate any path alias with a '@' so that it's distinguishable from other relative paths. I say this, because an import from "commonlib/src" is not obvious to be a path alias, and could simply be a relative path from the local src. But, "@commonlib/src" is easily recognized as a path alias, since '@' is not a legal leading folder/file character.

Madel answered 7/10, 2022 at 16:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.