By default, ZIPing the project directory will included all of your devDependencies
. slowing your upload speed to a crawl as you upload an enormous bundle containing 80% useless code (unless you're testing in production™ )
You only need your production dependencies when deploying, but need you devDependencies
for development. But you have to deploy from the same directory, and it must be named node_modules
. How can slim down the ol' deploy bundle?
Here's a horrible but effective hack that accomplishes this:
- We'll create an additional directory called
node_modules__prod
for storing production dependencies. - When we deploy we swap the names of the dev and production
node_modules
directories 😱, so the deploy tool stupidly uploads what it thinks is our fullnode_modules
but actually is our production-only modules directory. - When deploy is done (or fails) we swap the directory names again, restoring us back to development mode with full
devDependencies
again.
export $(egrep -v '^#' .env | xargs) # Read vars from .env
rm function.zip # Clean up previous build
# Module folder name swap
mv node_modules node_modules__stash_while_building
mv node_modules__prod node_modules
zip -r function.zip \
app.js \
node_modules \ # Now using production-only deps
package.json
echo "🌀 Uploading..."
aws lambda update-function-code \
--function-name=$LAMBDA_FUNCTION_NAME \
--profile=$AWS_CLI_UPLOAD_CODE_PROFILE \
--region=$LAMBDA_REGION \
--zip-file=fileb://function.zip && \
echo "✅ Deploy complete"
# Unswap the directories again, and we're back to dev mode
mv node_modules node_modules__prod
mv node_modules__stash_while_building node_modules
This script assumes the AWS CLI is installed and a
.env
containing$LAMBDA_FUNCTION_NAME
,$AWS_CLI_UPLOAD_CODE_PROFILE
and$LAMBDA_REGION
Remember to add
node_modules__prod
andnode_modules__stash_while_building
to your.gitignore
Hey! But now these two directories can get out of sync!
Here's a script that will run any NPM command against both directories, keeping them in sync.
Here's how you use it:
./npmDuo.sh install lodash.get
./npmDuo.sh uninstall lodash.get
And here's the script itself. Add it to your project directory.
echo "npmDuo: Running command in dev node_modules..."
npm $1 $2
# Swap
mv node_modules node_modules__stash_while_installing
mv node_modules__prod node_modules
echo "npmDuo: Running command in production node_modules..."
npm $1 --production $2
# Unswap
mv node_modules node_modules__prod
mv node_modules__stash_while_installing node_modules
echo "npmDuo Done"
Remember to give
./npmDuo.sh
execute permissions withchmod +x ./npmDuo.sh