It’s nice to be able to use yarn instead of npm on a CI server, but often you need root access to npm install -g yarn. Here is a bash script you can use, to install yarn (if not present) and then run “yarn”:

#!/bin/bash # Choose which version of yarn you want to use

EXPECTED_YARN_VERSION="0.16.1"



function install_yarn {

mkdir -p .yarn

DOWNLOAD_URL="https://github.com/yarnpkg/yarn/releases/download/v$EXPECTED_YARN_VERSION/yarn-v$EXPECTED_YARN_VERSION.tar.gz"

echo "Downloading from $DOWNLOAD_URL"

curl -fL $DOWNLOAD_URL > .yarn/yarn.tar.gz

tar zxf .yarn/yarn.tar.gz --strip-components=1 -C .yarn

}



if [ -f .yarn/bin/yarn ]; then

YARN_VERSION=$(node -e 'const fs = require("fs"); console.log(JSON.parse(fs.readFileSync(".yarn/package.json")).version);')

if [ "$YARN_VERSION" != "$EXPECTED_YARN_VERSION" ]; then

echo "The yarn version is $YARN_VERSION, expected $EXPECTED_YARN_VERSION. Re-downloading"

rm -rf .yarn

install_yarn

fi

else

echo "The file .yarn/bin/yarn does not exist, installing yarn".

install_yarn

fi



./.yarn/bin/yarn

The script will:

Create a folder “.yarn” in your working directory, where it will download yarn itself (It can be a good idea to gitignore this directory if you don’t want to explicitly commit it) Check if yarn is already installed. If it is already installed, check which version of yarn is installed. If it’s the wrong version, then it will delete this version. Attempt to download the correct version of yarn. Run yarn.

Things you can tweak in the script

Change EXPECTED_YARN_VERSION to another version if you want a newer or older yarn release to be used. Instead of downloading yarn every time it’s not present, you can commit the whole .yarn folder into the git repository, so that it is already present for the CI server to use. Change the download URL, if you want to host the yarn tar.gz file on a local proxy, like Nexus. Change the last command, so it can run yarn with arguments.

Good luck!