0

我正在使用 yarn v2 工作区,我的工作区之一是使用create-react-app/构建的前端react-scripts。我想在前端应用程序中启用绝对导入,所以我可以做类似的事情,import Button from 'components/Button'而不是import Button from '../../../components/Button'. 请注意,我的问题与跨工作区导入无关

我已按照CRA 文档中的说明启用绝对导入,并且一切正常,除了tsc

  • ✅ 应用程序运行

  • ✅ 应用程序构建

  • ✅ 测试通过

  • yarn tsc --noEmit在任何绝对导入上都会出现这样的错误:

    error TS2307: Cannot find module 'components/Button' or its corresponding type declarations.
    

这也会导致我的编辑器(vscode)中的 import 语句下出现红色波浪线。

我的项目结构是这样的:

package.json
tsconfig.json
workspaces/
  - backend
  - frontend
    - package.json
    - tsconfig.json
    - src/
      - components/Button.tsx
      - pages/PageWithAButton.tsx

这是根tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true
  }
}

还有前端tsconfig.json

{
  "extends": "../../tsconfig.json",
  "compilerOptions": {
    "jsx": "react-jsx",
    "baseUrl": "src"
  },
  "include": ["src"],
  "references": [{ "path": "../shared" }]
}

我从根目录使用这个命令调用 tsc:

yarn tsc --noEmit --jsx preserve

如何让 tsc 解析绝对导入?

4

2 回答 2

1

根据 Yarn 2+ 文档,建议通过别名和(TypeScript)路径映射链接协议: https ://yarnpkg.com/features/protocols#why-is-the-link-protocol-recommended-over-aliases-for-路径映射

最好paths从您的中删除,tsconfig.json而不是添加到package.json

"dependencies": {
  ...
  "components": "link:./src/components"
}

之后你应该运行

yarn

使更改package.json生效

于 2021-07-29T17:07:41.690 回答
0

compilerOptionstsconfig.json,您添加path如下:

"paths": {
  "components/*": ["src/components/*"]
}
于 2021-07-17T02:27:15.103 回答