How to make VSCode auto import work in a lerna-yarn-typescript project?

Viewed 1177

I have a lerna monorepo project with the following structure:

├─ packages
│    ├─ backend
│    │   ├─ package.json
│    │   ├─ tsconfig.json
│    │   └─ src
│    │      └─ index.ts
│    └─ shared
│        ├─ package.json
│        ├─ tsconfig.json
│        └─ src
│           └─ index.ts
├─ lerna.json
├─ package.json
├─ tsconfig.base.json
└─ tsconfig.json

I want to access interfaces declared in shared from the backend package.

packages/shared/src/index.ts:

export interface IPerson {
  name: string;
  doSomething: () => void;
}

But if I try to use the interface from the backend package vscode auto import won't show any suggestions.

packages/backend/src/index.ts:

screenshot from VSCode

If I import it manually like : import { IPerson } from '@example/shared/src/index'; it works like a charm.

Any ways to make VSCode recognise my shared project and suggest auto imports?

Here are the important files from the project:

/tsconfig.json:

{
    "extends": "./tsconfig.base.json",
    "compilerOptions": {
      "baseUrl": "./packages",
      "paths": {
        "@example/backend": ["backend/src"],
        "@example/shared": ["shared/src"],
        "@example/*": ["*/src"]
      },
    },
    "references": [
      {
        "path": "./packages/backend"
      },
      {
        "path": "./packages/shared"
      }
    ]
  }

/lerna.json:

{
  "packages": [
    "packages/*"
  ],
  "private": true,
  "version": "0.1.0",
  "npmClient": "yarn",
  "useWorkspaces": true
}

/packages/backend/package.json:

{
  "name": "@example/backend",
  "version": "0.1.0",
  "main": "index.js",
  "license": "MIT",
  "dependencies": {
    "@example/shared": "^0.1.0"
  },
  "devDependencies": {
    "tsconfig-paths": "^3.9.0",
    "typescript": "^4.1.3"
  }
}

/packages/backend/tsconfig.json:

{
    "extends": "../../tsconfig.json",
    "references": [
        { "path": "../shared" }
    ]
}

/packages/shared/tsconfig.json:

{
    "extends": "../../tsconfig.json",
    "compilerOptions": {
        "composite": true
    }
}

Thanks very much for any help!

1 Answers

There's a setting introduced in https://github.com/microsoft/TypeScript/pull/40637#issuecomment-717459902 to add a vscode setting "project-relative"

.vscode/settings.json

"typescript.preferences.importModuleSpecifier": "project-relative"

tsconfig.json

    "baseUrl": "./" /* Base directory to resolve non-absolute module names. */,
    "composite": true,
    "paths": {
      "@package-name/package-a": ["./packages/package-a/src"],
      "@package-name/package-b": ["./packages/package-b/src"]
    },
Related