Issue with sam build --build-in-source

Author: aleguern-azivkoCreated Sep 26, 2024Updated Sep 3, 2026
Labelstype/bugarea/buildmaintainer/need-response

When running sam build --build-in-source, the build process fails for the lambda function with an esbuild error. However, sam build without the --build-in-source flag works successfully.

Steps to reproduce: Set up a SAM project with multiple lambda functions using esbuild. Run sam build --build-in-source

Expected behavior: The build process should complete successfully for all lambda functions.

Actual behavior:

The build fails with the following error:
CopyNodejsNpmEsbuildBuilder:EsbuildBundle failed
EsbuildExecutionError: Esbuild Failed: ✘ [ERROR] Could not resolve "@sendgrid/client"

node_modules/@sendgrid/mail/src/classes/mail-service.js:6:25:
  6 │ const {Client} = require('@sendgrid/client');
    ╵                          ~~~~~~~~~~~~~~~~~~

You can mark the path "@sendgrid/client" as external to exclude it from the bundle, which will remove this error. You can also surround this "require" call with a try/catch block to handle this failure at run-time instead of bundle-time.

Environment: npm version: 10.5.0 SAM CLI version: 1.124.0 Operating System: macOS

Relevant configuration: SAM template snippet for the Contact function:

  Type: AWS::Serverless::Function
  Properties:
    Environment:
      Variables:
        SENDGRID_API_KEY: !Ref SendGridApiKey
    Events:
      Contact:
        Type: Api
        Properties:
          RestApiId: !Ref Api
          Path: /contact
          Method: post
          Auth:
            Authorizer: NONE
  Metadata:
    BuildMethod: esbuild
    BuildProperties:
      Minify: true
      Target: 'es2022'
      Sourcemap: false
      EntryPoints:
        - src/public/contact/index.ts

Relevant dependencies from package.json:

"dependencies": {
  "@sendgrid/mail": "^7.7.0",
  "esbuild": "^0.17.17"
},
"devDependencies": {
  "@types/aws-lambda": "^8.10.145",
  "typescript": "^4.5.5"
}