typescripttscnpm-workspaces

NPM Workspace monorepo: TSC fails with module not found for imports in library


I have the following setup for the npm monorepo: https://github.com/ChristianKernDev/monorepo_playground

Everything works as expected, except the tsc command, which shows the following error: ../common/src/index.ts:1:17 - error TS2307: Cannot find module 'test/a' or its corresponding type declarations.

This means, that the compiler can not correctly import direct paths in a submodule. How can i fix this?


Solution

  • There are multiple points:

    1. Your workspace setup works without running npm link. See relevant docs. Just running npm install is enough.
    2. Add a reference to common lib in app/tsconfig.json:
    {
      "extends": "../tsconfig.json",
      "compilerOptions": {
        ...
      },
      "references": [
        { "path": "../common" }
      ],
      "include": [
        ...
      ]
    }
    
    1. Now for the reference to work make the following changes in base tsconfig
    {
      "compilerOptions": {
        ...
        "emitDeclarationOnly": true,
        "composite": true
      },
    }
    
    1. Now you could build all the workspaces using the following command in project root:
    npm run --workspaces