Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How nestjs configures path aliases in a project

Tags:

nestjs

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.

like image 502
januw a Avatar asked Oct 15 '25 07:10

januw a


2 Answers

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.

like image 52
januw a Avatar answered Oct 18 '25 03:10

januw a


TL;DR;

  1. Update your package.json

"start:dev": "nest start --watch --exec 'node -r tsconfig-paths/register -r ts-node/register ./src/main.ts'"

  1. Use npm run start:dev
like image 26
Alexander Domrachev Avatar answered Oct 18 '25 04:10

Alexander Domrachev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!