DEV Community

Cover image for Alias your module directory with Node standard import mapping
Phyo Thiha
Phyo Thiha

Posted on

Alias your module directory with Node standard import mapping

If you've ever struggled with requiring/importing files using long, nested relative paths, you're in the right place. In this article, I'll show a method for importing files using standard Node.js solution—no need to rely on additional packages. The import mapping is available starting from Node.js 12+, offers a cleaner way to import files and works for both require and import (ESM), but for packages that have large numbers of subpaths, this might cause package.json bloat and maintenance issues.

Let's say you have the directory structure.

node_modules/
src/
  controllers/
    user.controller.js
  routes/
    users.route.js
  models/
    user.model.js
  services/
    user.service.js
test/
.env
index.js
package.json
Enter fullscreen mode Exit fullscreen mode

Firstly, define imports property in package.json. In the codes below, #root is the project root, #src houses the source code, and #controllers is the specific directory.

{
  "imports": {
    "#root/*.js": "./*.js", 
    "#src/*.js": "./src/*.js", 
    "#controllers/*.js": "./src/controllers/*.js"
  }
}
Enter fullscreen mode Exit fullscreen mode

Require/import it file using the path alias.

// users.route.js
const express = require("express");
const router = express.Router();
const userController = require("#src/controllers/user.controller.js");

router.get("/users/profile", userController.getProfile);

module.exports = router;
Enter fullscreen mode Exit fullscreen mode

Note: Do not forget .js extension when you import or require a file.

If you have "type": "module" in the package.json file, you should use import syntax. If you don't, you should use require syntax. Adding "type": "module" to the package.json enables ES 6 modules. For more info, see here.

Top comments (0)