Typescript 模块导入 - 嵌套项目中没有自动完成 architecture/npm-workspaces

Typescript module import - no auto-completion in nested project architecture/npm-workspaces

我有一个相当复杂的设置,其中包含许多分布式 npm 包,它们相互依赖。我试图尽可能地分解它。设置如下所示(每个子项目都有自己的 package.json):

Project-root:
- package.json*
- /apps: - app1
         - app2
- /common
- /libs: - lib1
         - lib2

应用程序:每个应用程序都是独立的,使用所有库和公共库,每个应用程序都有自己的 package.json

通用:用于共享组件,但仅限于应用程序(依赖于所有库)

Libs: 在其他项目和 apps/common、WIP 中使用的私人 npm 包,因此 used/included 通过 npm-workspaces/git 克隆。因为它们是由 workspaces

通过 npm install 添加的

我遇到的问题是,typescript/tsc在“通用”模块中的所有类中抛出错误ts(2307)。

import { BarInterface } from '@mynamespace/lib1/foo';

Cannot find module '@mynamespace/lib1/foo' or its corresponding type declarations.

一切正常,dev/build 运行没有错误,但是 Visual Studio Code/Intellisense and/or tsc 无法共同接受提供的进口声明。因此,我们高度依赖自动完成功能,因为新开发人员应该很容易进入该项目。

* package.json(根):

{
  "name": "main-project",
  "workspaces": [
    "./apps/*",
    "./libs/*",
    "./common"
  ]    
}

* package.json (库):

{
  "name": "@mynamespace/lib1",
  "exports": {
    "./foo": "./src/foo/index.ts",
  },   
}

* package.json(常见):

{
  "name": "main-project-common",
  "exports": {
    "./bar": "./src/bar/index.ts",
  },
  "dependencies": { 
    "@mynamespace/lib1": "^1.0.0"
    "@mynamespace/lib2": "^1.0.0"
  }   
}

* package.json (app1):

{
  "name": "app1",
  "exports": {
    "./bar": "./src/bar/index.ts",
  },
  "dependencies": { 
    "@mynamespace/main-project-common": "file:../../common"
  }   
}

所有 tsconfig.json 文件如下所示:

{
  "compilerOptions": {
    "target": "es2018",
    "module": "esnext",
    "lib": ["es2017", "dom", "dom.iterable"],
    "declaration": true,
    "emitDeclarationOnly": true,
    "outDir": "./types",
    "rootDir": "./src",
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "experimentalDecorators": true,
    "forceConsistentCasingInFileNames": true,
    "useDefineForClassFields": false,
    "resolveJsonModule": true,
    "noImplicitAny": false
  },
  "include": ["src/**/*.ts", "global.d.ts"],
  "exclude": []
}

vite.config.js

import { defineConfig } from 'vite';
import path from 'path';

// https://vitejs.dev/config/
export default defineConfig({
  build: {
    target: 'esnext',
    lib: {
      entry: path.resolve(__dirname, 'src/index.ts'),
      formats: ['es'],
    },
    rollupOptions: {
      external: /^lit/,
    },
  },
});

我是不是漏掉了什么,或者是设置太复杂了,还是打字稿不支持某种反模式?

我发现了问题。我错过了公共模块模块声明

使用以下内容将文件 global.d.ts 添加到 /common 解决了我的问题。

declare module '*';

每个打字稿模块都需要此步骤。