serverless-sharp icon indicating copy to clipboard operation
serverless-sharp copied to clipboard

Package as an NPM

Open tyrauber opened this issue 5 years ago • 0 comments

serverless-sharp is a really useful library. I've used it for a bunch of different purposes.

One thing I like to do is include it as a package in other serverless applications, as most apps need to serve and resize images. For example, a use case where you have a serverless app with a koa.js API on one function and Koa/Vue.js SSR front-end on another. It's useful to mount serverless-sharp on a third endpoint, for example, on the path 'public', and deploy everything to one API Gateway / Cloudfront instance, instead to having to deploy and manage another instance.

Here is how I do it. Perhaps there is a better way though.

Implementation

Install serverless-sharp from the repo (Would be cool to install directly from npm!):

npm install https://github.com/venveo/serverless-sharp --save

Install the linux version of sharp (Important!):

npm install --arch=x64 --platform=linux sharp

Using serverless.yml as an exmaple, change the SharpLayer path to point to the LambaLayer:

layers:
  sharp:
    path: ./node_modules/serverless-sharp/lambdaLayers/SharpLayer

Modify the function to use the serverless-sharp node_module. You can package this function individually, excluding all other node_modules in this function, except serverless-sharp and sharp:

      exclude:
        - node_modules/**
        - '!node_modules/serverless-sharp/**'
        - '!node_modules/sharp/**'

You also need to modify the handler to use the node_module.

handler: node_modules/serverless-sharp/src/index.handler

You can also update the events path so it doesn't conflict with the rest of your app. For example, having all images served from public:

events:
      - http:
          path: /public/{any+}

Voila. Serverless-sharp mounted as a function in another serverless application.

Total function and layer size should be approximately.

Serverless: Uploading service index.zip file to S3 (35.71 MB)...
Serverless: Uploading service sharp.zip file to S3 (921.37 KB)...

That's how I do it. Is there a better way?

tyrauber avatar May 26 '20 17:05 tyrauber