Search code examples
javascriptnode.jspathserverless

Is there any possibility to avoid multiple ../ when we are importing a function?


I want to avoid this thing at importing a function

const ApiError = require('../../../../classes/ErrorClass');

Is any possibility to use,I don't know Ex:

require('mypath/ErrorClass')

If I have 11 imports I don't want to have something like this

const ApiError = require('../../../../classes/ErrorClass');
const ex= require('../../../classes/ApiClass');
const ex1= require('../../../../utils/utils');
const ex2= require('../../../etc/etc');
const ex3= require('../../../../../etc/etc');
const ex4= require('../../../../etc/etc');
const ex5= require('../../../../etc/etc');
const ex6= require('../../../../etc/etc');

Thank you!


Solution

  • Yes, you can do it with package.json. Imagine you have the following structure:

    my-app/
    ├─ src/
    │  ├─ index.js
    │  ├─ node_modules/
    │  ├─ dir/
    │  │  ├─ nested/
    │  │  │  ├─ nestedMod.js
    │  ├─ function/
    │  │  ├─ myMod.js
    │  │  ├─ myMod3.js
    │  │  ├─ myMod2.js
    ├─ package.json
    

    You have to add the imports field in package.json

    {
      "name": "my-app",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "author": "",
      "license": "ISC",
      "imports": {
        "#nestedMod": "./src/dir/nested/nestedMod.js",
        "#myFunc": "./src/function/myMod.js",
        "#myFunc2": "./src/function/myMod2.js",
        "#myFuncs/*": "./src/function/*.js"
      }
    }
    
    

    then you can do:

    const nestedMod = require('#nestedMod')
    const myFunc = require('#myFunc')
    const myFunc2 = require('#myFunc2')
    const myFunc3 = require('#myFuncs/myMod3')
    

    P.S.: Only works in Node