Skip to content

Instantly share code, notes, and snippets.

@mattbryson
Last active November 2, 2022 21:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattbryson/9b7028ba7022704ddf01e82cb7cb8d42 to your computer and use it in GitHub Desktop.
Save mattbryson/9b7028ba7022704ddf01e82cb7cb8d42 to your computer and use it in GitHub Desktop.
SAM Lambda Function make file to support node_modules in Layers
##
# Custom SAM Build function to support ES modules in Lambda Layers
#
# SAM deploy does not support symlinks in Lambda Functions, it tries to follow them at deploy time
# This means you cant build a function with a symlink to the node_modules of a layer - which you need to do to support ES modules
# @see https://github.com/vibe/aws-esm-modules-layer-support
#
# This works by packaging the function code as SAM does using `npm pack`, but then we insert a symlink to the layers node_modules
# And then create a zip *including* the symlink to the layer.
#
# By renaming the zip file to match the ARCHIVE_PATH SAM will still find the built source, but as its already a zip it wont try to package it
#
# Rename MyLambdaFunction to mach the Logical ID of your Lambda Function
build-MyLambdaFunction:
# package the same way SAM does using npm pack (which supports .npmignore files etc), saving the resulting archive name as ARCHIVE
$(eval ARCHIVE_PATH=$(shell npm pack))
# Unpack again so we can make it Lambda compatible
tar -xzvf "$(ARCHIVE_PATH)"
# Insert our symlink to layer node modules
ln -s /opt/nodejs/node_modules package/node_modules
# create a zip with no root folder (npm pack adds a 'package' root folder that we dont want)
cd package && zip -ry ../lambdaFunctionSrc.zip .
# delete the ARTIFACTS_DIR created by SAM
rm -rf "$(ARTIFACTS_DIR)"
# replace ARTIFACTS_DIR with our ZIP file
mv lambdaFunctionSrc.zip "$(ARTIFACTS_DIR)"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment