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:
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:
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.
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',
},
};