How to use short paths for importing in Nx Workspace?

Viewed 4876

I have created an NX Workspace using Angular preset. Where I have one app and two libraries. Inside my app, I am trying to use shorter paths for import.

With my current approach inside my app, I can use short paths for all files and folders for my app only. Whenever I am trying to import any library inside my app getting this error - 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"]
}

App's - 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/*"]
        }
}

App's - 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"]
}

App's Module

// 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';
2 Answers

Unfortunately tsconfig path's are overwritten when extended, instead of the array being extended. So when you provide paths in an app's tsconfig, it is overriding the paths in the base tsconfig, hence your libraries are not being found.

A workaround for this is to just copy the library paths from tsconfig.base.json, but there is nothing on the Nx side to get around this.

Related