[AWS Lambda] We recommend npm install serverless --global to reduce node_modules file size
To reduce file size when deploying to AWS Lambda with Serverless Framework, we recommend npm install serverless —global.
Just to include it in package.json and manage it under git, I was installing serverless with:
npm install serverless --save
Since official documentation and many technical blogs recommend npm install serverless —global, I think including it in package.json is the minority approach.
For two reasons: “speeding up” serverless deploy and “saving network traffic”.
While this wasn’t noticeable with good network environments, both points became concerning when developing in tethering environments, so I decided to improve it.
Remove it from package.json with npm uninstall —save, then globally install with npm install —global.
npm uninstall serverless --save
npm install serverless --global
# npm install [email protected] --global
When serverless was locally installed, the .zip file was 66.57 MB including other node modules.
$ $(npm bin)/serverless deploy --verbose
Serverless: Packaging service...
Serverless: Excluding development dependencies...
Serverless: Creating Stack...
Serverless: Checking Stack create progress...
CloudFormation - CREATE_IN_PROGRESS - AWS::CloudFormation::Stack - aws-nodejs-dev
CloudFormation - CREATE_IN_PROGRESS - AWS::S3::Bucket - ServerlessDeploymentBucket
CloudFormation - CREATE_IN_PROGRESS - AWS::S3::Bucket - ServerlessDeploymentBucket
CloudFormation - CREATE_COMPLETE - AWS::S3::Bucket - ServerlessDeploymentBucket
CloudFormation - CREATE_COMPLETE - AWS::CloudFormation::Stack - aws-nodejs-dev
Serverless: Stack create finished...
Serverless: Uploading CloudFormation file to S3...
Serverless: Uploading artifacts...
Serverless: Uploading service .zip file to S3 (66.57 MB)...
# Takes time with poor internet connection… ⏳
When changing serverless to global install, the .zip file was 56.59 MB including other node modules. I was able to reduce file size by about 10 MB.
$ serverless deploy --verbose
Serverless: Packaging service...
Serverless: Excluding development dependencies...
Serverless: Uploading CloudFormation file to S3...
Serverless: Uploading artifacts...
Serverless: Uploading service .zip file to S3 (56.59 MB)...
# 66.57 - 56.59 = 9.98 MB file size reduction
That’s all from the Gemba where we want to reduce node_modules file size and speed up serverless deploy.