Install Netlify functions dependencies

Hello, everyone…

I organize my lambda functions into a folder called /functions at the root of my project.

For each function I create a folder (inside /functions folder) with the name of the function and a JS file with the same name of the function.

Functions have their own dependencies and for that I create a package.json file inside the folder of each function.

Also, the project has its own package.json width its dependencies.

I have something like this:


package.json (Project dependencies)

/ functions /
  + / function-one / 
      - function-one.js
      - package.json (Function dependencies)
  + / function-one / 
      - function-one.js
      - package.json (Functions dependencies)
    ...

To make everything work properly, I have to install the project’s dependencies and the function’s dependencies.

To do that I have the following scripts configured in my package.json:

...

"scripts": {
  "preinstall": "npx netlify-lambda install",
  "dev": "netlify dev",
  "build": "npx ng build --prod"
  },

...

With the “preinstall” script I force the installation of the function dependencies using netlify-lambda when run “npm install”.

Everything works for me locally and when I upload the project to production.

The problem I find is when sometimes, in the build process, Netlify decide to load the dependencies from the cache and not execute the “npm install” command (therefore neither “npm preinstall”).

This is a good thing as it saves time installing dependencies, but only copies from the cache the project dependencies and not the function dependencies.

Then after finishing the build process, the functions do not have their dependencies installed correctly and cause an error.

I added a new “prebuild” script to my package.json.

...

"scripts": {
  "preinstall": "npx netlify-lambda install",
  "dev": "netlify dev",
  "prebuild": "npx netlify-lambda install",
  "build": "npx ng build --prod"
  },

...

This way I force the installation of the function dependencies before the build process. Even if the project dependencies have been installed from cache.

But this is not a good solution. In case the dependencies are not loaded from cache, the process of installing function dependencies is repeated and this takes time delaying the publication of my site.

My questions are:

1.- What’s the right way to do this?

2.- Why when the dependencies are loaded from cache only the project dependencies are copied and not the individual function dependencies?

3.- When does Netlify decide to load the cache dependencies and not run an npm install?

Thanks.

Hi @existo,

We always run your build command. We only automatically run npm install if your package.json changes or your clear the cache.

What is the Netlify build script you’re running? Also what’s the netlify site and the repo (if it’s public).