Search code examples
nestjs

How nestjs configures path aliases in a project


I configured the path alias in tsconfig.json of the nestjs project, but there was an error while running.

I tried to configure like Angular, but there was an error in nestjs

This is my tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es6",
    "sourceMap": true,
    "outDir": "./dist",
    "baseUrl": "./",
    "incremental": true,
    "paths": {
      "~auth/*": ["src/auth/*"]
    }
  },
  "exclude": ["node_modules"]
}

Use it like this

import { userLoginJwt } from '~auth/jwt-names'

Startup error

$ npm run start:dev
[0] internal/modules/cjs/loader.js:584
[0]     throw err;
[0]     ^
[0]
[0] Error: Cannot find module 'src/auth/jwt-names'

Sorry, I emphasize here that running npm run start works fine, but running npm run start:dev can lead to unexpected situations.


Solution

  • This job, I work:

    1. Modify my 'tsconfig.json'
    {
      "compilerOptions": {
        "module": "commonjs",
        "declaration": true,
        "removeComments": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "target": "es6",
        "sourceMap": true,
        "outDir": "./dist",
        "baseUrl": "./src",
        "incremental": true,
        "paths": {
          "~auth/*": ["auth/*"]
        }
      },
      "exclude": ["node_modules"]
    }
    
    1. Add 'tsconfig-paths-bootstrap.js' file
    // tsconfig-paths-bootstrap.js
    
    const tsConfig = require('./tsconfig.json');
    const tsConfigPaths = require('tsconfig-paths');
    
    tsConfigPaths.register({
      baseUrl: tsConfig.compilerOptions.outDir,
      paths: tsConfig.compilerOptions.paths,
    });
    
    1. Modify the 'nodemon.json' file
    {
      "watch": ["dist"],
      "ext": "js",
      "exec": "node  -r ./tsconfig-paths-bootstrap.js dist/main.js"
    }
    
    1. Use path alias
    import { userLoginJwt } from '~auth/jwt-names';
    

    Now executing the npm run start:dev error has disappeared.