3

take note: inside src folder

I want to achieve module aliasing name instead of using require("../../services"), require("../../models").

i want to achieve something like this: require("@services"), require("@models");

How to achieve this on serverless framework with node js without using webpack or babel

1 Answer 1

0

There is a way to add alias to your node.js project :

You need to do three things. Add a jsconfig.json file at te root of your project, add _moduleAliases option and the module-alias lib inside your package.json and finally import the lib at the very top of your index.js.


1. Library installation

Run the following command to install the lib :

npm i --save module-alias

2. Jsconfig.json

Add a jsconfig.json will help your IDE to detect that you are using aliases. Here is an example of jsconfig.json file :


{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": [
        "common/*"
      ],
      "@routes/*": [
        "common/routes/*"
      ],
      "@utils/*": [
        "common/utils/*"
      ],
      "@helper/*": [
        "common/helper/*"
      ],
      "@hooks/*": [
        "common/hooks/*"
      ]
    }
  },
  "include": [
    "common/**/*"
  ]
}


3. package.json

It is here that the magic happened. In your package.json file add the following lines.

It is important to be synchronised with the jsconfig.json file in order to get fully working aliases. !


  ...
  "_moduleAliases": {
    "@": ".",
    "@routes": "common/routes",
    "@utils": "common/utils",
    "@hooks": "common/hooks",
    "@helper": "common/helper"
  },
  "depedencies": {
   ...
   "module-alias": "^2.2.2" #Latest current version
   ...
  },
  ...

4. Index.js

At the very top of your index.js file add the following code :

require('module-alias/register')
...

This normally should do the trick

If needed, see the documentation here :

Sign up to request clarification or add additional context in comments.

2 Comments

Hi @Hades, in serverless framework, we don't have index.js since it is invoking per lambda function (api endpoint). how to achieve without using index.js
Sorry for this late response. Can you provide a folder structure ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.