Error: darwin-x64' binaries cannot be used on the 'linux-x64' platform (AWS lambda + typescript + webpack sharp module )

Viewed 3291

aws lambda with typescript is occured error when bundle by webpack.

Before bundle webpack, I did "npm i --arch=x64 --platform=linux --target=12.14.1 sharp" and labmda is working properly.

But, lambda upload zip size is more and more larger.

so, I want to resize lambda upload zip size using serverless-webpack.

Image lambda is working well except using sharp module.

I don't know how to do.

I did:

  1. Delete node_modules and package-lock.json and install dependencies ( also installed sharp )
  2. Delete node_modules/sharp and install sharp ( lambda environment - linux, x64, node version )
  3. Set serverless-webpack configuration in serverless : packagerOptions ( scrips ) - rebuild sharp lambda enviroment

But, lambda is not working properly.

and I looked many informations.

[lambda linux env]
Error running Sharp inside AWS Lambda function: darwin-x64' binaries cannot be used on the 'linux-x64' platform

[Serverless-webpack]
https://github.com/serverless-heaven/serverless-webpack/issues/396

Thank you!


[Edit]

My local env : Mac

production env : linux

Maybe, I think that npm command with "--platform" is not working in mac.

Additionally, I solved this problem using aws codebuild.

I posted answer.

But, It is not working in my local [ Mac ]

4 Answers

I got it working by telling webpack to reinstall the package after it runs npm install:

webpack:
  includeModules:
    forceExclude:
      - aws-sdk
  packagerOptions:
    scripts:
      - rm -rf node_modules/sharp
      - npm install --arch=x64 --platform=linux sharp

I solved this problem using aws codebuild.

codebuild has linux and node.js runtime.

So, I ran below command in aws codebuild ( https://sharp.pixelplumbing.com/install )

rm -rf node_modules/sharp
npm install --arch=x64 --platform=linux sharp

sharp module works properly.

I got it working by using sam cli to build using this command

sam build -u

This command builds the code inside a container that has the similar environments as lambda

Dave Cowart's answer helped me a lot but having multiple lambda functions in the repo, I didn't want to install sharp into all of my functions.

Here's my solution:

serverless.yml

  webpack:
    webpackConfig: 'webpack.config.js'
    includeModules:
      forceExclude:
        - aws-sdk
    packagerOptions:
      scripts:
        - rm -rf node_modules/sharp
        - npm install --production --arch=x64 --platform=linux

You don't actually need to specify sharp in the install script. Making it a generic npm install means it will only reinstall sharp if it's in the package.json (which it won't be if it's not used due to webpack tree shaking).

Related