Not able to access Typescript files from another project - Project references

Viewed 610

I am trying to access types defined in another project in a mono-repo. Here's how projects are structured

-- packages
   -- project-a
      -- tsconfig.json
   -- project-b
      -- tsconfig.json
   -- shared
      -- src
         -- UserModel.ts
         -- index.ts
      -- tsconfig.json
   -- tsconfig.base.json
-- package.json
-- tsconfig.json (Default no changes here)

tsconfig.base.json

{
    "extends": "../tsconfig.json",
    "compilerOptions": {
      "declaration": true,
      "declarationMap": true,
      "emitDecoratorMetadata": true,
      "module": "commonjs",
      "noEmit": false,
      "composite": true
    },
    "files": [],
    "references": [{ "path": "./shared" }]
  }

shared tsconfig.json

{
  "extends": "../tsconfig.base.json",
  "compilerOptions": {
    "outDir": "lib",
    "baseUrl": "./",
    "rootDir": "src",
    "composite": true,
    "experimentalDecorators": true,
    "declaration": true,
    "declarationMap": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "**/__tests__/*", "**/__e2e__/*"]
}

project-a tsconfig.json

{
  "extends": "../tsconfig.base.json",
  "compileOnSave": true,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "downlevelIteration": true,
    "allowSyntheticDefaultImports": true,
    "experimentalDecorators": true,
    "module": "es2020",
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2015",
    "jsx": "react", 
    "lib": [
      "es2018",
      "dom"
    ],
    "paths": {
      "@shared": ["../shared/src"]
    }

  },
  "angularCompilerOptions": {
    "fullTemplateTypeCheck": true,
    "strictInjectionParameters": true
  },
  "references": [
    { "path": "../shared" }
  ]   
}

Even after all these settings when I try and reference UserModel.ts from shared project in project-a, IDE just doesn't recognize UserModel.ts

Import line in project-a import {UserModel} from '@shared/UserModel'; //Even tried 'shared/src/UserModel'

How do I solve this issue?

2 Answers

please change and try

project-a tsconfig.json

    "paths": {
      "@shared/*": ["packages/shared/src/*", "packages/shared/src"]
    }

I can get that folder structure to compile using:

packages/project-a/tsconfig.json

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@shared/*": ["../shared/src/*"]
    }
  }
}

packages/shared/tsconfig.json

I could compile it without any content in this tsconfig

{}

tsconfig.json

{
  "files": [],
  "references": [
    { "path": "packages/project-a" },
    { "path": "packages/shared" }
  ]
}

Both my IDE and the typescript CLI (npx tsc --build) had absolutely no problem with it.

I'm not sure what exactly your issue is, but maybe you can use this as a starting point?

This post is quite helpful: https://stackoverflow.com/a/64637923/10315665

Related