how make aws build ignore my dev dependencies

Viewed 975

I have a standard (hello-world) package.json for my aws lambda app:

{
  "name": "hello_world",
  "version": "1.0.0",
  "description": "hello world sample for NodeJS",
  "main": "app.js",
  "repository": "https://github.com/awslabs/aws-sam-cli/tree/develop/samcli/local/init/templates/cookiecutter-aws-sam-hello-nodejs",
  "author": "SAM CLI",
  "license": "MIT",
  "dependencies": {
    "axios": "^0.21.1"
  },
  "scripts": {
    "test": "mocha tests/unit/"
  },
  "devDependencies": {
    "chai": "^4.2.0",
    "mocha": "^8.2.1"
  }
}


However if I run npm i, it creates node_modules folder within this hello-world folder which is deployed to AWS lambda when I run sam deploy.

It is not needed because I keep all necessary dependencies in a separate layer. However if I delete them, then I can't test locally (sam local start-api) because the app raises an exception since it can't find the dependencies. What should I do to avoid node_modules to be deployed to AWS but still have a possibility to run it locally?

2 Answers

As a quick fix you could run npm prune --production before you deploy and a npm install afterwards.

Option 1:

Before deploying, remove node_modules folder and run npm install --only=prod command which will install only dependencies and will ignore devDependencies. Then deploy your app.

Option 2:

Install chai and mocha globally on your local machine and remove them from package.json at all. This will allow you to use those modules during local development.

I'd recommend to use the first option, because you will not need to install every single dev dependency globally. I'd also recommend you to setup any CI/CD (e.g. AWS CodeBuild) for build/deployment of your project and stop doing that from your local machine - that way you will not need to clean node_modules every time and you will have convenient general development process.

Related