首页 > 解决方案 > Typescript build issue with lerna

问题描述

I currently have a lerna/react/TS project of the following structure:

.
├── lerna.json
├── package.json
├── packages
│   ├── patient
│   │   ├── package.json
│   │   ├── src
│   │   │   └── index.tsx
│   │   ├── tsconfig.build.json
│   │   └── tsconfig.json
│   └── appointment
│       ├── package.json
│       ├── src
│       │   └── index.tsx
│       ├── tsconfig.build.json
│       └── tsconfig.json
├── tsconfig.build.json
└── tsconfig.json

In packages/appointment/src/index.tsx its importing the patient module:

import { Patient } from '@ui-sdk/patient';

when running the build command tsc --project ./tsconfig.build.json inside the appointment folder, its adding the patient code again.

Actual:

/packages/appointment/dist/patient/index.js
/packages/appointment/dist/appointment/index.js

Expected:

/packages/appointment/dist/index.js

The build config at the /packages/appointment/tsconfig.build.json is as follows:

{
  "extends": "../../tsconfig.build.json",

  "compilerOptions": {
    "outDir": "./dist",
    "jsx": "react",
    "esModuleInterop": true
  },

  "include": [
    "src/**/*"
  ]
}

and the main tsconfig.json at the root level:

{
  "compilerOptions": {
    "module": "esnext",
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "skipLibCheck": true,
    "sourceMap": true,
    "resolveJsonModule": true,
    "moduleResolution": "node",
    "declaration": true,
    "baseUrl": ".",
    "paths": {
      "@ui-sdk/*": ["packages/*/src"]
    },
  },

  "exclude": [
    "node_modules",
    "dist"
  ]
}

If I remove this section:

"baseUrl": ".",
    "paths": {
      "@ui-sdk/*": ["packages/*/src"]
    },

The compilation throws an error

packages/appointment/src/index.tsx(2,24): error TS2307: Cannot find module '@ui-sdk/patient' or its corresponding type declarations.

Any idea how to make the build contain only the codes for that component only, instead of bringing the other files in the build folder?

标签: reactjstypescripttsconfiglerna

解决方案


我刚刚遇到了同样的问题。问题是我不得不从tsconfig.build.json文件中省略“路径”。

tsconfig.json

{
  "extends" "./tsconfig.build.json",
  "compilerOptions": {
    "paths": {
      "@ui-sdk/*": ["packages/*/src"]
    }
  }
}

tsconfig.build.json

{
  "compilerOptions": {
    // ...
  }
}

这导致 TS 不会尝试解析您的本地包,而是将其视为对外部包的引用。


推荐阅读