DEV Community

Cover image for Fix long import paths in your NestJS project #nestjs
tkssharma
tkssharma

Posted on

Fix long import paths in your NestJS project #nestjs

Taming the Import Jungle: Simplifying Long Import Paths in NestJS

Introduction

As your NestJS projects grow in size and complexity, managing long import paths can become cumbersome and error-prone. Fortunately, NestJS provides a convenient solution to streamline your imports and enhance code readability: path aliases. In this blog post, we'll explore how to effectively use path aliases to simplify your NestJS project's import structure.

Understanding Path Aliases

Path aliases allow you to create custom shortcuts for frequently used paths within your project. Instead of specifying lengthy relative paths, you can use a shorter alias, making your imports more concise and easier to maintain.

Setting Up Path Aliases in NestJS

  1. Configure tsconfig.json:
    • Open your project's tsconfig.json file and add the baseUrl and paths properties:
   {
     "compilerOptions": {
       "baseUrl": "./src",
       "paths": {
         "@app/": ["src/app"],
         "@modules/": ["src/modules"],
         // Add more aliases as needed
       }
     }
   }
Enter fullscreen mode Exit fullscreen mode
  1. Use Aliases in Imports:
    • Replace long import paths with their corresponding aliases. For example:
   // Before:
   import { MyService } from './modules/my-module/my.service';

   // After:
   import { MyService } from '@modules/my-module/my.service';
Enter fullscreen mode Exit fullscreen mode

Best Practices for Path Aliases

  • Choose meaningful aliases: Use clear and concise aliases that reflect the structure of your project.
  • Avoid circular references: Ensure that your aliases do not create circular dependencies.
  • Update aliases as needed: As your project evolves, update your aliases to reflect changes in the directory structure.
  • Use a linter: Configure your linter to enforce consistent path alias usage.

Benefits of Using Path Aliases

  • Improved readability: Shorter and more concise imports make your code easier to understand.
  • Reduced errors: Fewer typos and mistakes when dealing with long paths.
  • Enhanced maintainability: Easier to refactor and reorganize your project.
  • Consistent naming conventions: Promotes a consistent naming structure throughout your project.

Conclusion

Github
https://github.com/tkssharma/nestjs-advanced-2023/tree/main/apps/23-nestjs-path-mapping

By effectively using path aliases in your NestJS projects, you can significantly improve code readability, maintainability, and reduce the likelihood of errors. This simple technique can have a substantial impact on the overall quality and efficiency of your development process.

Top comments (1)

Collapse
 
titobundy profile image
titobundy • Edited

Hi, I've some questions about this topic:

  1. What is the difference (functional) between using alias or absolute path, like import 'src/modules/...'
  2. In the most recent version of nestjs (v9, v10), is there any problem with testing (jest) or in production mode?
  3. Is this issue still valid? github.com/nestjs/typescript-start...

I joined a project (currently not deployed in any environment), nest v10, where team used absolute paths, but the tests didn't work (linux, macos), I had to add moduleNameMapper jest config in package.json:

"jest": {
    "moduleNameMapper": {
      "^src/(.*)$": "<rootDir>/../src/$1"
    },
    "moduleFileExtensions": [
      "js",
      "json",
      "ts"
    ],
    "rootDir": "src",
    "testRegex": ".*\\.spec\\.ts$",
    "transform": {
      "^.+\\.(t|j)s$": "ts-jest"
    },
    "collectCoverageFrom": [
      "**/*.(t|j)s"
    ],
    "coverageDirectory": "../coverage",
    "testEnvironment": "node"
  }
Enter fullscreen mode Exit fullscreen mode

The project not use any package like module-alias.
With this configuration the tests work again, and I can run test, build, start:prod, lint, format, etc.

But I still have doubts about whether it is a good practice or whether it will cause some kind of errors in the future in production.