在 AWS Elastic Beanstalk 使用 Yarn 安裝 Node.js 套件

最近在嘗試使用 Beanstalk 跑 Node.js 遇到一點貧頸是 Beanstalk 預設只會使用 npm 如此對於安裝套件上有點麻煩,如果使用 Yarn 可以解決掉很多問題,所以就研究一下如何在 Beanstalk 使用 Yarn。

新增 prebuild 檔案

基本上要使用 Yarn 很簡單只需要新增一個腳本到 prebuild 資料夾下面就可以了,如果有其他想要在 prebuild 之前執行的也可以都把腳本塞塞進去。這邊範例是新增檔案 .platform/hooks/prebuild/yarn.sh,檔案內容如下:

#!/bin/bash

# install node
curl --silent --location https://rpm.nodesource.com/setup_18.x | bash -;

# install yarn
curl --silent --location https://dl.yarnpkg.com/rpm/yarn.repo | tee /etc/yum.repos.d/yarn.repo;
yum -y install yarn;

# install node_modules with yarn
app="$(/opt/elasticbeanstalk/bin/get-config container -k app_staging_dir)";
cd "${app}";
echo "App: ${app}."
yarn --production;

上面使用到一個 Beanstalk 的指令,在 Beanstalk 有很多指令可以用來取得參數它的指令樣子如下

$ /opt/elasticbeanstalk/bin/get-config command [ options ]

而因為我們要取得執行個體的值所以使用 /opt/elasticbeanstalk/bin/get-config container 再使用 –key (-k) 就可以取得特定的 key 值,這邊我們要取得 app_staging_dir 也就是 App 的資料夾所以使用 /opt/elasticbeanstalk/bin/get-config container -k app_staging_dir

檔案資料夾結構

整體完成後資料夾如下,打包後上傳就會發現 Beanstalk 使用 Yarn 來安裝套件了。

~/my-app/
|-- index.js
`-- .platform/
    `-- hooks/                # Application deployment hooks
        `-- prebuild/
            `-- yarn.sh

參考資料