Package a function individually with only those node_modules used

Hello team,

I’m finding quite useful to use serverless to manage a constellation of lambdas and a API Gateway. The issue I’m facing right now is that those lambdas have different node_modules, and I’d like to package only those related to each function.

I have tried with some of the existing plugins (and most of the answers on this forum pointed there too) like serverless-webpack and serverless-bundle. They do an amazing job, but we find very useful when debugging the logs to know which line failed, so we would happily sacrifice on the package size and not optimize the function. I also tried serverless-plugin-include-dependencies but for some reason it was adding many other dependencies not related to that function (nor even related to those declared on the package.json)

Still, it is important that a lambda function only packages those node_modules used on that individual lambda function (thus package: individually: true).

A potential solution we have explored and worked for us is to have a per lambda package.json file where we declare the node_modules used on that particular lambda function, npm i each lambda folder and include it. I’m wondering if there’s a recommended way to do this without custom scripts.

This current solution needs a config with this:
(Using serverless 1.57.0)
Extract of serverless.yml:

  individually: true
  excludeDevDependencies: false
    - coverage/**
    - .circleci/**
    - tests/**

    name: mobile-authorize-${self:provider.stage}
    description: API Gateway Lambda Authorizers
    handler: src/mobile-user-authorize/index.handler
        - ./**
        - src/mobile-user-authorize/**

Is there anyway we can package only the dependencies used by each lambda, without uglyfing the code? Also, what’s your recommended way, adding individual package.json, or using a plugin?

Thanks in advance!

Edit: I’m giving another chance to serverless-plugin-include-dependencies as I just understood those extra packages belong to a peer dependency (so great job adding those, actually). Keeping the post open just in case somebody had any suggestion :wink:

1 Like