21

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?

J V
  • 703
  • 2
  • 7
  • 12

2 Answers2

8

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

user571188
  • 91
  • 1
  • 5
  • 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](https://github.com/microsoft/TypeScript/issues/20110). – Paul Razvan Berg Oct 20 '22 at 09:48
4

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.