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.

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more