23

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?

2 Answers 2

8

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

1
  • 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. Commented Oct 20, 2022 at 9: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.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.