Problem: a lot ../ using require or import in Javascript

const { DoSomething } = require("../../lib/do-something");

… happy with that

const { DoSomething } = require("@lib/do-something");

Fun fact: Typescript is navite support path alias and you just setup with file tsconfig.json and VSCode support also.

How about with JavaScript?

Using package module-alias

  1. Install package
npm install module-alias
  1. Setup path alias in file package.json
{
  "name": "path_alias",
  "version": "1.0.0",
  "description": "Setup path alias with Javascript",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "module-alias": "^2.2.2"
  },
  "_moduleAliases": {
    "@api": "./api",
    "@lib": "./lib"
  }
}
  1. Require package in top of the main file (index.js) before any code.
require("module-alias/register");

TADA Now you can running your code without error wth

Hold on, but you can go to define in VSCode

wth

Let try with file jsconfig.json and enjoy

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["./*"],
      "@api/*": ["./api/*"],
      "@lib/*": ["./lib/*"]
    }
  }
}

Source code: https://github.com/chuongtrh/path_alias