Switching Between Yarn and NPM

Intro

This post is not going to cover the differences between NPM and Yarn, or how to use them. We are just going to go over the process of switching from one to the other.

Things you can’t delete

packge.json

Let’s start by talking about the package.json file. Do not delete this file. Ever.

This file describes the dependencies that your app requires as well as startup scripts, and is used mutually by both Yarn and NPM. Do not ever delete this file.

Things you can delete

yarn.lock & package-lock.json files

These are the files that are created by NPM and Yarn respectively for their own purposes. These are auto generated and you can delete them at any time, and simply have them be automatically generated again. No worries.

These files are generated during the install process.

node_modules folder

This is where the actual packages live after they are installed. However you can install them as many times as you like. So don’t worry about deleting this folder, it is automatically generated and can be regenerated easily.

This folder is generated during the install process.

Switching Between Package Managers

If you want to switch from NPM to Yarn follow these steps.

  1. delete the node_modules folder
  2. delete the package-lock.json file
  3. run yarn install

This will generate a new node_modules folder and a yarn.lock file. Your project is now using yarn.

If you want to switch from Yarn to NPM follow these steps.

  1. delete the node_modules folder
  2. delete the yarn.lock file
  3. run npm install

This will generate a new node_modules folder and a package-lock.json file. Your project is now using NPM.

Additional Items that may need changing

If you are using Docker you will also need to make updates to your Dockerfile.

For example a NPM based Dockerfile may look like this

FROM node:18-alpine

WORKDIR /app
EXPOSE 3001

COPY package*.json ./

# make node modules and give node user permission
RUN mkdir -p /app/node_modules
RUN chown node:node /app/node_modules

RUN npm install
COPY . .

# run as user node
USER node

CMD [ "npm", "start"]

while a Yarn based Dockerfile may look like this

FROM node:18-alpine

WORKDIR /app
EXPOSE 3001

COPY package*.json ./

# make node modules and give node user permission
RUN mkdir -p /app/node_modules
RUN chown node:node /app/node_modules

RUN yarn install
COPY . .

# run as user node
USER node

CMD [ "yarn", "start"]