Leo's dev blog

Simplify your Node.js project with module aliases

White and black one way printed road signages
Published on
/3 mins read/---

Recently, I have been working on a pet project using Node.js on the backend to further my knowledge and prevent skill degradation during my free time. However, I encountered a frustrating issue with paths that many developers have likely experienced.

import { saveUser } from '../../../../../models/User'
import homeController from '../../../../../controllers/home'

This code can be a headache for developers who need to determine how many folders to traverse to find the desired file. If you need to move a file to a different folder, you must update the path in all files that import the module .

But what if we could define aliases (i.e., shortcuts) for frequently imported modules throughout the entire project?

For example:

import { saveUser } from '@models/User'
import homeController from '@controllers/home'

In which:

  • @models is equivalent to ./src/models/*

  • @controllers is equivalent to ./src/controllers/*.

The solution is quite simple with module-alias and a tsconfig.json configuration. Follow these instructions to set it up:

Update tsconfig.json

Open the tsconfig.json file and add the following configuration to the compilerOptions object:

tsconfig.json
"compilerOptions": {
  // other configs...
  "baseUrl": "./src",
  "paths": {
      "*": [
          "node_modules/*",
          "src/types/*"
      ],
      "@controllers/*": [
          "controllers/*"
      ],
      "@models/*": [
          "models/*"
      ]
  }
}

Here, @controllers and @models are aliases for your modules (you can use any naming convention you like, and it does not have to start with @ — that's just the prefix I use to differentiate).

Now you can use the configured alias in your project, but you will encounter a module import error:

[Node] Error: Cannot find module '@models/User'

Install the module-alias package

This package resolves path aliases in JS files after they are compiled.

  • Install it with:

    npm i --save module-alias # or yarn add module-alias
  • Configure it in package.json:

    package.json
    "_moduleAliases": {
      "@models": "dist/models",
      "@controllers": "dist/controllers"
    }

Note that dist/ is the folder that contains your code after it has been built (depending on your configuration, it could be dist/, build/, etc.).

  • Finally, register the module in your app:

    import 'module-alias/register'

Import it only once in your project's start file (such as index.ts, app.ts, or server.ts...).

Done

Now you can reload your IDE, start the project, and use aliases across your project.

VS Code Recommendation

VS Code supports this feature by reading the tsconfig.json file. Simply reload it to use the feature.

Good luck!

Refs