#StackBounty: #serverless #aws-lambda-layers Build Lambda Layer with Serverless

Bounty: 100

What is the correct way to build lambda layer with Serverless framework for NodeJS?

  1. Do we need to add package.json in layer specific folder and install dependencies manually. This means I will be duplicating many dependencies in layer’s package.json with project root’s package.json content and manual install in both locations.
  2. How can I use project’s node_modules directory without dev dependencies. If I specify "path" : "node_modules" in layers, layer zip file is around 69MB and includes all dev dependencies. I tried excludeDevDependencies true and false combinations without success.

Directory structure:

project/
    ├── README.md
    ├── iamRoleStatements.ts
    ├── layer
        ├── node_modules
        ├── package-lock.json
        └── package.json
    ├── node_modules
    ├── package.json
    ├── plugins.ts
    ├── resources.ts
    ├── serverless.ts
    ├── src
    ├── tsconfig.json
    ├── tsconfig.paths.json
    └── webpack.config.js

Below is my serverless.ts file.

import hello from "@functions/hello";
import type { AWS } from "@serverless/typescript";
import iamRoleStatements from "iamRoleStatements";
import plugins from "plugins";
import resources from "resources";

const serverlessConfiguration: AWS = {
  service: "foo-apis",
  frameworkVersion: "2",
  custom: {
    webpack: {
      webpackConfig: "./webpack.config.js",
      includeModules: false,
    },
    prune: {
      automatic: true,
      number: 3,
    },
  },
  plugins,
  provider: {
    name: "aws",
    runtime: "nodejs14.x",
    apiGateway: {
      minimumCompressionSize: 1024,
      shouldStartNameWithService: true,
    },
    environment: {
      NODE_PATH: "/opt/nodejs/node_modules:/opt/node_modules",
      AWS_NODEJS_CONNECTION_REUSE_ENABLED: "1",
    },
    lambdaHashingVersion: "20201221",
    iamRoleStatements,
    tracing: {
      lambda: true,
      apiGateway: true,
    },
  },
  package: {
    individually: true,
    // without explicity excludeDevDependencies false, few packages such as uuid, long were missing.
    excludeDevDependencies: false,
  },
  layers: {
    nodejs: {
      name: "nodejs",
      path: "layer",
      description: "API NodeJS dependencies",
      compatibleRuntimes: ["nodejs14.x"],
    },
  },
  // import the function via paths
  functions: { hello },
  resources,
};

module.exports = serverlessConfiguration;

Serverless version:

~#serverless --version
serverinfo  serverless  servertool
Serverless: Running "serverless" installed locally (in service node_modules)
Framework Core: 2.57.0 (local)
Plugin: 5.4.4
SDK: 4.3.0
Components: 3.17.0


Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.