Hackernoon logoHow to use yarn in a project, without installing yarn by@eiriksletteberg

How to use yarn in a project, without installing yarn

Eirik Sletteberg Hacker Noon profile picture

@eirikslettebergEirik Sletteberg

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”:

# Choose which version of yarn you want to use

function install_yarn
mkdir -p .yarn
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);')
echo "The yarn version is $YARN_VERSION, expected $EXPECTED_YARN_VERSION. Re-downloading"
rm -rf .yarn
echo "The file .yarn/bin/yarn does not exist, installing yarn".


The script will:

  1. 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)
  2. 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.
  3. Attempt to download the correct version of yarn.
  4. Run yarn.

Things you can tweak in the script

  1. Change EXPECTED_YARN_VERSION to another version if you want a newer or older yarn release to be used.
  2. 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.
  3. Change the download URL, if you want to host the yarn tar.gz file on a local proxy, like Nexus.
  4. Change the last command, so it can run yarn with arguments.

Good luck!

Hacker Noon is how hackers start their afternoons. We’re a part of the @AMIfamily. We are now accepting submissions and happy to discuss advertising &sponsorship opportunities.
To learn more, read our about page, like/message us on Facebook, or simply, tweet/DM @HackerNoon.
If you enjoyed this story, we recommend reading our latest tech stories and trending tech stories. Until next time, don’t take the realities of the world for granted!


Join Hacker Noon

Create your free account to unlock your custom reading experience.