How to package only required (or Dev) dependencies with serverless servcice

Hello,
I’ve an application with sls/aws/nodejs

At first the app structure was straight forward, one service like:

  • MY-APP-ROOT-FOLDER
    – node_modules
    – src
    — lib
    — endpoints
    ---- handlers
    – serverless.yml
    – package.json

and it was working fine, till i ran into “limited resources 200” problem on AWS, that i had to take action and split my service into two services like that:

  • MY-APP-ROOT-FOLDER
    – node_modules
    – services
    — service1
    ---- endpoints
    ---- serverless.yml
    — service2
    ---- endpoints
    ---- serverless.yml
    – src
    — lib
    – serverless.yml
    – package.json

when i first try to deploy that modified structure, it doesn’t recognize some modules, so i had to include “node_modules” folder and “src” folder, myself, in every serverless.yml like:

package:
include:
- …/…/node_modules/**
- …/…/src/**

It worked actually, BUT, it results in a big size for the package as it packages the whole node_modules folder!!
I knew that in the first structure, it was packaging only required dependencies, resulting in a less package size.

My Questions is:
1- is my structure right, by using one package.json at root
2- If so, what is the proper way to package only required dependencies in both services (do i have to include it like i did, or it can be installed on cloud after deploy ?)

For my multi service monorepos I always use serverless-webpack plugin to package my Lambdas and set package: individually:true. The webpack tree shaking ensures that only the modules needed by each Lambda is bundled, resulting in optimised package sizes.

I also have started to just keep a single package.json with this approach which keeps dependency management simpler.

1 Like

Thanks for your reply,
I’m kinda not expert with webpack, is there any detailed examples or tutorials on how to package using serverless-webpack ?

Check out the serverless-webpack plugin repo.
Basically you install the plugin, add some config to your serverless.yml and create a webpack.config.js file in the same folder.
Here’s a basic webpack.config.js that I have used for Javascript projects:

const path = require('path');
const slsw = require('serverless-webpack');

module.exports = {
    entry: slsw.lib.entries,
    externals: /^aws-sdk.*$/i, // aws-sdk is already available in Lambda environment, so don't bundle it
    target: 'node',
    mode: slsw.lib.webpack.isLocal ? 'development' : 'production',
    output: {
        libraryTarget: 'commonjs2',
        path: path.join(__dirname, '.webpack'),
        filename: '[name].js',
        sourceMapFilename: '[file].map',
    },
};

And the key parts of serverless.yml:

...
plugins:
    - serverless-webpack
package:
    individually: true

custom:
    webpack:
        includeModules: false
1 Like