如何在 Nx Workspace 中使用短路径导入?

RAH*_*NDU 9 angular nrwl nrwl-nx

我使用 Angular 预设创建了一个 NX 工作区。我有一个应用程序和两个库。在我的应用程序中,我尝试使用较短的路径进行导入。

使用我的应用程序中当前的方法,我可以仅对我的应用程序的所有文件和文件夹使用短路径。每当我尝试在我的应用程序中导入任何库时都会出现此错误 -Cannot find module or its corresponding type declarations.

tsconfig.base.json

{
    "compileOnSave": false,
    "compilerOptions": {
        "rootDir": ".",
        "sourceMap": true,
        "declaration": false,
        "moduleResolution": "node",
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "importHelpers": true,
        "target": "es2015",
        "module": "esnext",
        "lib": ["es2017", "dom"],
        "skipLibCheck": true,
        "skipDefaultLibCheck": true,
        "baseUrl": ".",
        "paths": {
            "@extranet/leftbar": ["libs/extranet/leftbar/src/index.ts"],
            "@extranet/topbar": ["libs/extranet/topbar/src/index.ts"]
        }
    },
    "exclude": ["node_modules", "tmp"]
}
Run Code Online (Sandbox Code Playgroud)

应用程序 - tsconfig.json

compilerOptions": {
        "baseUrl": "src",
        "forceConsistentCasingInFileNames": true,
        "strict": true,
        "noImplicitReturns": true,
        "noFallthroughCasesInSwitch": true,
        "paths": {
            "@app/*": ["app/*"],
            "@core/*": ["app/core/*"],
            "@env/*": ["environments/*"],
            "@shared/*": ["app/shared/*"],
            "@config/*": ["app/configs/*"]
        }
}
Run Code Online (Sandbox Code Playgroud)

应用程序 - tsconfig.app.json

{
    "extends": "./tsconfig.json",
    "compilerOptions": {
        "outDir": "../../dist/out-tsc",
        "types": [],
        "paths": {
            "@app/*": ["app/*"],
            "@core/*": ["app/core/*"],
            "@env/*": ["environments/*"],
            "@shared/*": ["app/shared/*"],
            "@config/*": ["app/configs/*"]
        }
    },
    "files": ["src/main.ts", "src/polyfills.ts"],
    "include": ["src/**/*.d.ts"]
}
Run Code Online (Sandbox Code Playgroud)

应用程序的模块

// Auth layout & Admin Layout imports
// These imports are working fine
import { AuthLayoutComponent } from '@core/layouts';
import { WithLeftbarLayoutComponent } from '@core/layouts';
import { WithoutLeftbarLayoutComponent } from '@core/layouts';

// Library imports for templates
// With these two imports I am getting error
import { ExtranetTopbarModule } from '@extranet/topbar';
import { ExtranetLeftbarModule } from '@extranet/leftbar';
Run Code Online (Sandbox Code Playgroud)

Cra*_*ola 20

不幸的是,扩展时 tsconfig 路径被覆盖,而不是扩展的数组。因此,当您在应用程序的 tsconfig 中提供路径时,它会覆盖基本 tsconfig 中的路径,因此找不到您的库。

解决此问题的方法是仅从 tsconfig.base.json 复制库路径,但 Nx 端没有任何方法可以解决此问题。

  • 这让我今天免于数小时的头痛 (7认同)