Excluding the AWS SDK from a Serverless Package

Chris Shepherd
Aug 6 · 2 min read

When developing your AWS Lambda functions using Serverless you want them to be as small as possible to reduce cold start time. Using the serverless-webpack plugin you can use Webpack to include everything in one minified file. This is great and will definitely help with those cold start times.

However, there is even more you can do. AWS include the aws-sdk in the Node.js runtime. This means you don't need to include it yourself, which is good because it can easily add about 3MB on to your deployment package. This information is covered in the README for serverless-webpack but I've found it doesn't work. Instead you can apply some Webpack knowledge by using the externalsproperty. For a Serverless project using Babel using the stock example from serverless-webpack your webpack.config.js would look something like this:

const path = require("path");
const slsw = require("serverless-webpack");
module.exports = {
entry: slsw.lib.entries,
externals: [{ "aws-sdk": "commonjs aws-sdk" }], // <-- additional line
target: "node",
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: [
{
loader: "babel-loader",
},
],
},
],
},
output: {
libraryTarget: "commonjs",
path: path.join(__dirname, ".webpack"),
filename: "[name].js",
},
};

This will fully exclude the aws-sdk from your bundle and massively reduce the size of your functions. If you do sls package before and after adding the externals property you should see savings of about 3MB. One thing to bear in mind is that the version AWS provide might not always be the latest. It's probably best to keep the same version AWS use in your devDependencies to be as close to production as possible.

Chris Shepherd

Written by

Developer from Middlesbrough, living in London. Mostly interested in React, Node and the web.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade