How To Get Serverless to recognise "import" in Node JS

I have a simple Graph QL API which I want to upload to AWS Lambda, however, before getting anywhere near deployment…

However, I am struggling to even run the simple local query of:

serverless invoke local -f graphql -p query.json

I get the following error:

It seems that Serverless is unable to recognise imports from subdirectories in Node: apolloServer.js relies on imports from subdirectories such as utils, api, graphql etc…

It would be almost impossible to have all the code in the single apolloServer.js file.

Is there a way to make Serverless recognise imports from subdirectories in Node ?

Does it work when you deploy to actual Lamba e.g. is this a bug in serverless-local ?

Have you seen the docs on the package part of serverless.yml ? You can include any files in the deployment package, though we’d usually exclude whole “src” folders, and/or copy the bits needed to a “dist” and refer to them from there; YMMV.

The “import” statement is a part of the ECMAScript module system and is not supported by default in Node.js runtime v12 and below. To use the “import” statement in a serverless environment, you need to use a transpiler such as Babel to convert your code to a format that can be understood by Node.js.

Here’s a general outline of the steps you can follow to get serverless to recognize “import” in Node.js:

  1. Install required packages: Install the following packages using npm:

npm install @babel/core @babel/cli @babel/preset-env

  1. Create a .babelrc file: In the root of your project, create a .babelrc file with the following contents:

{
“presets”: [
[
@babel/preset-env”,
{
“targets”: {
“node”: “12”
}
}
]
]
}

  1. Transpile your code: Transpile your code using Babel from the command line:

npx babel src --out-dir dist

  1. Update your serverless configuration: In your serverless.yml file, update the “handler” field to point to the transpiled code in the “dist” folder:
    functions:
    hello:
    handler: dist/handler.default
    events:

    • http:
      path: /
      method: get
  2. Deploy your code: Deploy your serverless application as usual.

This should allow you to use the “import” statement in your Node.js code and have it work in a serverless environment. Note that this is a general outline, and you may need to make additional changes to your code or configuration depending on your specific requirements. I have detailed about it in this article you can also check for further enhancement.