Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running AWS Lambda with layers using NodeJS in VSCode on local machine

My project's structure is next:

MyProject
  layers
    myLayer1
      nodejs
        node_modules
          myLayer1
            myExtension.js
  lambda1
    handler.js
  lambda2
    handler.js
  jsconfig.json

myExtension.js

module.exports.myTest = () => {
  return 'My extension test';
};

handler.js

const myext = require('myLayer1');
module.exports.handler = async (event) => {
  return {
    statusCode: 200,
    body: JSON.stringify({
      message: myext.myTest()
    })
}};

When I deploy to AWS - things are working. But I'm unable to run/debug it on my local machine.

According to what I found the jsconfig.json file should help to map paths in this case, but VSCode/NodeJS ignore it whatever I wrote there (I tried to place it the MyProject root folder and within lambda folders).

I can run this lambdas locally if I change the 'require' within the handler.js to:

const myext = require('./layers/myLayer1/nodejs/node_modules/myLayer1');

which obviously breaks the code when I deploy it to AWS.

like image 264
Kamarey Avatar asked Nov 06 '22 06:11

Kamarey


1 Answers

Overview

This is similar to another question that is looking for how to reference modules from multiple layers: How configure Visual Studio Code to resolve input paths for AWS Lambda Layers (javascript)

The simpler answer, for a lambda function with a single layer for node_modules, is to use a jsconfig.json file in the directory where the lambda's package.json file with no dependencies is located (this is not the root of the entire project, but the root of the lambda function project only).

The example project of the question does attempt to use a jsconfig.json file but it should be in the lambda1 and lambda2 directories, while the question has this file located at the top-level, which does not have the desired effect.

Example jsconfig.json file for VS Code

This file should be placed at both of the following locations for the example project in the question:

  • MyProject/lambda1/jsconfig.json
  • MyProject/lambda2/jsconfig.json
// https://code.visualstudio.com/docs/languages/jsconfig
{
  "compilerOptions": {
    // baseUrl is the path used for pathless / naked node module includes
    "baseUrl": "../layer/node_modules/",
    "moduleResolution": "node",
    "module": "commonJS"
  }
}

Complete Example Code / Project Structure

https://github.com/pwrdrvr/layers-js-demo

like image 160
huntharo Avatar answered Nov 12 '22 16:11

huntharo