使用 VS Code 使用 nx 创建的下一个应用程序的相对导入

Relative imports on next app created with nx using VS Code

我在使用 nx 和 VS Code 引导的 Next.js 项目时遇到问题:

当我尝试使用 VS Code 自动导入组件时,它会生成一个绝对导入,立即触发 @nrwl/nx/enforce-module-boundaries eslint 规则,使当前文件无效。

例如,文件夹结构:

apps/my-app/
  pages/
    entity/
      new/
        index.tsx
  components/
    Loading.tsx

生成的导入将是:

// in my-app/pages/entity/new/index.tsx
import Loading from 'apps/my-app/components/Loading'

虽然我期待:

import Loading from '../../../components/Loading'

VS Code 有一个始终使用相对路径导入的设置,但这会阻止我以正确的方式导入库 (@scope/lib)。

是否有任何可能的设置可以使自动导入按预期工作?

您可以在项目根目录的 tsconfig.base.json 文件中配置 paths 属性。如果将它添加到其他 tsconfig 文件中,它将不起作用,正确的是项目根目录中的 tsconfig.base.json 文件。

离开您的示例,您可以将以下内容添加到 paths 选项。

"@my-app/*": ["apps/my-app/*"]

现在您可以将 ../../../components/Loading 更改为 @my-app/components/Loading

更详细的示例(注意:为了便于阅读,我删除了应该在您的 tsconfig.base.json 文件中的其他一些选项)

{
    "compilerOptions": {
        "baseUrl": ".",
        "paths": {
            "@my-app/*": [
                "apps/my-app/*"
            ]
        }
}

官方 TS 手册中的来源和更多信息:https://www.typescriptlang.org/docs/handbook/module-resolution.html#path-mapping