Yarn is a node package manager that can be used in place of npm. Beyond the basic package management functionality, such as adding and removing dependencies it can also execute scripts to create applications, such as React apps. and build them (i.e. get them ready for deployment) as well as run them.
Creating package.json
To get started we would run the following command within the project’s folder to generate a package.json file (or create one yourself using your preferred text editor).
yarn init
You’ll be presented with a set of questions which will then result in the contents of the package.json file. These include your project name, version, description, git repository etc. If you don’t have any response to the questions just press enter, we can always fill in missing data later.
Here’s an example package.json file
{
"name": "MyProject",
"version": "1.0.0",
"description": "MyProject Description",
"main": "index.js",
"repository": {
"url": "https://myproject-repos",
"type": "git"
},
"author": "PutridParrot <emailaddress>",
"license": "MIT"
}
Adding dependencies
I said at the start of this post that yarn is a package manager, so obviously we’ll want to add some package dependencies. Again, we can add our information to the package.json directly using our preferred text editor or use the yarn application from the command line to do this. Ofcourse the yarn command does a little more, it will check the yarn registry (by default this is https://registry.yarnpkg.com/)
To add a package dependency we use
yarn add [package]
So for example, we can add React using
yarn add react
This results in the addition for the following to the package.json
"dependencies": {
"react": "^16.8.6"
}
Check out Packages to allow us to search for packages.
We can remove a package using
yarn remove react
Creating an application
We can also create an application. For example to create a React application (i.e. grabs the dependencies, generates the code etc.) we can use
yarn create react-app my-app
yarn create react-app my-app --typescript
Running scripts
We can also add scripts to the package.json, like this
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
}
Now we can execute scripts using
yarn start
There’s much more yarn can do, but this post covers the most often used commands (or at least the one’s I’ve used most so far).