Serverless Framework: How to add external NPM packages?

taptipblard picture taptipblard · May 11, 2016 · Viewed 14.7k times · Source

My situation is that I am having a bit of trouble in adding external NPM packages to my Serverless Framework project (specific package is geopoint).

I went to the root folder of the Serverless project and ran npm install geopoint --save. package.json got updated with dependencies": { "geopoint": "^1.0.1" } and node_modules folder was created.

My folder structure looks like this:
root-project-folder
-functions
--geospatial
---handler.js
-node_modules
--geopoint

In my functions/geospatial/handler.js I declared the geopoint module with:

    var geopoint = require('geopoint');
    var geopoint = require('../../geopoint');
    var geopoint = require('../../../geopoint');

The lambda console returns an error of:

    {
      "errorMessage": "Cannot find module '../../geopoint'",
      "errorType": "Error",
      "stackTrace": []
    }

How can I properly add external NPM modules to a Serverless Framework project?

Answer

e_m0ney picture e_m0ney · May 12, 2016

I think what you are experiencing is the same as what I was experiencing recently. I could install npm packages in my application root directory, but nothing would get deployed to lambda.

My understanding is that serverless deploys everything under each component directory (subdirectory under the application root). In your case, under functions.

I could not find much in the serverless documentation around this, but what I did was define a package.json file under my functions folder and then run an npm install in that subdirectory. Then after deploying to lambda, the node_modules under this directory got deployed too, meaning that my function code could require any of these npm modules.

So, your folder structure should now look like this:

root-project-folder
|-functions
|--package.json
|--node_modules
|---geopoint
|--geospatial
|---handler.js
|-package.json
|-node_modules
|--geopoint

The benefit here as well is that you can only deploy the npm dependencies that your functions need, without those that serverless needs to deploy your resources.

Hopefully that helps - once again, not sure this is best practise, just what I do because this isn't documented anywhere that I could find on the Serverless repository or in any example code.