Paul Razvan Berg
Paul Razvan Berg

Reputation: 21348

Understanding "baseUrl" and "paths" in TypeScript with * glob

I have a monorepo created with yarn workspaces and the following folder structure:

├── foo                   (workspace @project/foo)
│   ├── package.json
│   └── src
│       └── index.ts
├── bar                   (workspace @project/bar)
│   ├── package.json
│   └── src
│       └── index.ts
├── package.json          (monorepo root)
└── tsconfig.json         (base tsconfig)

And the following settings in tsconfig.json:

{
  "compilerOptions": {
    "baseUrl": ".",
    "module": "commonjs",
    "paths": {
      "@project/foo/*": "./packages/foo/src/*",
      "@project/bar/*": "./packages/bar/src/*"
    },
    ...
  }
}

In the @project/bar workspace, I want to import modules from @project/foo:

import foo from "@project/foo";

But I'm getting the following error:

Cannot find module '@project/foo' or its corresponding type declarations.ts(2307)

If I remove the * symbols from both the keys and the values of the "paths" object, the code compiles. Why is that? How can I keep the * glob pattern and make non-relative imports to my local modules?

Upvotes: 0

Views: 4929

Answers (1)

satanTime
satanTime

Reputation: 13539

roots should be defined separately because / blocks @project/foo from import, only @project/foo/ and @project/foo/something are allowed.

"@project/foo": "./packages/foo/src",
"@project/bar": "./packages/bar/src",
"@project/foo/*": "./packages/foo/src/*",
"@project/bar/*": "./packages/bar/src/*"

In case of monorepo you can't use /* because after compilation it won't be accessible in the same way as at runtime in monorepo.

The right way is to point to public_api of the projects

"@project/foo": "./packages/foo/src/public_api",
"@project/bar": "./packages/bar/src/public_api",

The same for subprojects:

"@project/foo/sub": "./packages/foo/src/sub/public_api",

Upvotes: 0

Related Questions