Levelling up Monorepos with npm Workspaces

Rate this content
Bookmark

Learn more about how to leverage the default features of npm workspaces to help you manage your monorepo project while also checking out some of the new npm cli features.

FAQ

NPM workspaces are a set of features in NPM that allow for managing multiple nested packages within a single top-level package. This helps in centralizing the installation of dependencies into a single node_modules folder and managing a single package lock file, making it ideal for handling monorepos.

NPM workspaces were first introduced in August 2020 with the release of NPM CLI version 7.0.

The key advantages of using NPM workspaces include centralized dependency management, a single package lock file for all sub-packages, and streamlined task management across multiple packages in a monorepo setup. This results in a more efficient and manageable development process.

To start a new workspace in NPM, use the `npm init` command inside your project. This ensures that every required folder and package.json file is correctly set up and listed in the workspaces field of your top-level package.json.

To add dependencies to a specific workspace, use the command `npm workspace <workspace_name> add <package_name>`. This command targets the specified workspace and installs the desired package directly into it, managing dependencies efficiently.

The NPM pkg command is used to set or retrieve key-value pairs from the package.json files of your workspaces. It can be particularly powerful for managing configurations and dependencies across multiple workspaces efficiently.

Yes, you can run scripts specifically for one workspace by using the command format `npm run --workspace=<workspace_name> <script_name>`. This allows for running tasks directly within the context of the specified workspace.

Both NPM and Yarn workspaces aim to solve similar problems related to managing monorepos. The main difference lies in their integration with their respective package managers. NPM workspaces are integrated with the NPM CLI, providing native support for managing node modules and dependencies in a unified manner.

Ruy Adorno
Ruy Adorno
33 min
25 Mar, 2022

Comments

Sign in or register to post your comment.

Video Summary and Transcription

NPM workspaces help manage multiple nested packages within a single top-level package, improving since the release of NPM CLI 7.0. You can easily add dependencies to workspaces and handle duplications. Running scripts and orchestration in a monorepo is made easier with NPM workspaces. The npm pkg command is useful for setting and retrieving keys and values from package.json files. NPM workspaces offer benefits compared to Lerna and future plans include better workspace linking and adding missing features.

1. Introduction to NPM Workspaces

Short description:

Hello, and welcome to leveling up monorepos with NPM workspaces. My name is Rui Aduno, a software developer in the NPM CLI team at GitHub. I have been working on NPM CLI for almost three years now. Let's start with an overview of NPM workspaces. Workspaces help you manage multiple nested packages within a single top-level package. It centralizes the installation of dependencies and allows you to run all tasks in a single place. We have been improving NPM workspaces since August 2020 with the release of NPM CLI 7.0. More improvements are coming.

Hello, and welcome to leveling up monorepos with NPM workspaces. Let me start by introducing myself. My name is Rui Aduno. I'm a software developer in the NPM CLI team at GitHub. I have been working on NPM CLI for almost three years now. I worked on the NPM v7 rewrite and a lot of those features that we're going to be talking about here today and especially in workspaces. I'm super excited to be sharing some of that work with you here today.

Let's start with an overview of what we're going to be covering here today. Let's start with an intro to what is in NPM workspaces and then cover some very practical examples trying to get as close to real-life usage as possible and also note some of the stuff that you should be looking forward to. So, let's get started.

NPM workspaces. What is it? So, let's start with workspaces, which is basically this concept introduced by Yarn a while ago and basically it is a way to help you manage many packages within a single repo and for NPM, NPM workspaces is kind of the broad name we gave, the set of features that help you achieve that, basically help you manage multiple nested package within a single top level package. So, it's going to help you centralize the installation of all the dependencies into a single node modules folder. So, you're going to end up also having only a single package lock file, and there are some advantages to that, it is definitely the ideal way for managing monorepos, and thanks to that you can have a single place to manage all your issues, and basically manage your project and your community. But also, into the technical side, you can also centralize, have a single place to run all your tasks, building, anything that you can kind of imagine, you kind of need everything together to get your project running with all the packages, you can have it all in a single place. So, it might help a lot depending on the style of the project you're trying to achieve. Another thing I would like to note here is the timeline, just to give a little bit of this notion of how we've been iteratively improving on NPM workspaces. And you can see it all started in August 2020 with the release of the 7.0 of the NPM CLI that first introduced support to installing NPM, the workspaces. And then in version 7.7, another big one, which kind of first introduced the configuration properties of a workspace or targeting all the workspaces and the first command that support them with NPM Run and NPM Exec. So there were many more, but I just kind of wanted to illustrate how we've been improving. And you can definitely wait to see more improvements coming on NPM Workspaces.

2. Adding Workspaces and Dependencies

Short description:

So let's get started with some examples here. I have this project that I have on the left-hand side here, that is a simple app that I put together trying to get as close as possible of a real-life project. This is kind of like a web app that consists of two different services. And with that I'm hoping to put some examples that are real close to how you would use this in your real life. Moving forward here, I'd like to highlight NPM Init. It's probably the best way of just starting your workspace. So I'm going to run a quick example here in my sample app. I'm going to create a new workspace. Let's say I'm going to call it the website. So I can run NPM init. And I'm targeting a website. So that's going to create a website folder with a package.json file inside it. And as I mentioned before, the other really important point that NPM init takes care of is placing the reference to the website inside my package.json file in my top level folder. So with that, it is all set up. If I npm install here, now the install tree is going to be tracking the website. And if I run npm ls again, I'm going to see website listed as one of the workspaces here highlighted in green. And we can move on to another very important aspect. How do you add dependencies to one of your workspaces? So a real quick example here again. I'm going to shift around the workspace configuration here, so you can see that you can practically go anywhere. So I can just declare an npm workspace, I'm going to target the website I just created.

So let's get started with some examples here. I have this project that I have on the left-hand side here, that is a simple app that I put together trying to get as close as possible of a real-life project. This is kind of like a web app that consists of two different services. So you can see I have my user sense service, my web app service, and I even configured a third workspace here, which is the slides that you're seeing right now. So they're all part of this monorepo app that I'm managing here.

And with that I'm hoping to put some examples that are real close to how you would use this in your real life. So you can see they all have a bunch of dependencies here using NextJS, the services using Fastify. So I can just quickly start by running NPM Ls here, and we can see how Ls is a command that is aware of workspaces, and it's going to highlight each of the workspaces in my project, and even list the dependencies of each workspace when I run NPM Ls. So it's the first command to know that has first class support for workspaces.

Moving forward here, I'd like to highlight NPM Init. It's probably the best way of just starting your workspace, because it's going to make sure every step that is needed is going to end up being there. So basically, everything you need to track a nested package as a workspace is make sure you have the folder with a package.json inside it, inside your project, and then just add that folder name to your workspaces field of your package.json in the top level. So using NPM init is going to make sure that those requirements are there. So I'm going to run a quick example here in my sample app. I'm going to create a new workspace. Let's say I'm going to call it the website. So I can run NPM init. I'm using dash y here to just accept all the defaults. And I'm targeting a website. So that's going to create a website folder with a package.json file inside it. It's going to print the contents of the package.json file over here. And as I mentioned before, the other really important point that NPM init takes care of is placing the reference to the website inside my package.json file in my top level folder. So with that, it is all set up. If I npm install here, now the install tree is going to be tracking the website. And if I run npm ls again, I'm going to see website listed as one of the workspaces here highlighted in green. So that is definitely the recommended way to get started with a new workspace inside your project.

And we can move on to another very important aspect. How do you add dependencies to one of your workspaces? So a real quick example here again. I'm going to shift around the workspace configuration here, so you can see that you can practically go anywhere. So I can just declare an npm workspace, I'm going to target the website I just created.

QnA

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

Automating All the Code & Testing Things with GitHub Actions
React Advanced Conference 2021React Advanced Conference 2021
19 min
Automating All the Code & Testing Things with GitHub Actions
Top Content
Code tasks like linting and testing are critical pieces of a developer’s workflow that help keep us sane like preventing syntax or style issues and hardening our core business logic. We’ll talk about how we can use GitHub Actions to automate these tasks and help keep our projects running smoothly.
Fine-tuning DevOps for People over Perfection
DevOps.js Conf 2022DevOps.js Conf 2022
33 min
Fine-tuning DevOps for People over Perfection
Top Content
Demand for DevOps has increased in recent years as more organizations adopt cloud native technologies. Complexity has also increased and a "zero to hero" mentality leaves many people chasing perfection and FOMO. This session focusses instead on why maybe we shouldn't adopt a technology practice and how sometimes teams can achieve the same results prioritizing people over ops automation & controls. Let's look at amounts of and fine-tuning everything as code, pull requests, DevSecOps, Monitoring and more to prioritize developer well-being over optimization perfection. It can be a valid decision to deploy less and sleep better. And finally we'll examine how manual practice and discipline can be the key to superb products and experiences.
Why is CI so Damn Slow?
DevOps.js Conf 2022DevOps.js Conf 2022
27 min
Why is CI so Damn Slow?
We've all asked ourselves this while waiting an eternity for our CI job to finish. Slow CI not only wrecks developer productivity breaking our focus, it costs money in cloud computing fees, and wastes enormous amounts of electricity. Let’s take a dive into why this is the case and how we can solve it with better, faster tools.
The Zen of Yarn
DevOps.js Conf 2022DevOps.js Conf 2022
31 min
The Zen of Yarn
In the past years Yarn took a spot as one of the most common tools used to develop JavaScript projects, in no small part thanks to an opinionated set of guiding principles. But what are they? How do they apply to Yarn in practice? And just as important: how do they benefit you and your projects?
In this talk we won't dive into benchmarks or feature sets: instead, you'll learn how we approach Yarn’s development, how we explore new paths, how we keep our codebase healthy, and generally why we think Yarn will remain firmly set in our ecosystem for the years to come.
End the Pain: Rethinking CI for Large Monorepos
DevOps.js Conf 2024DevOps.js Conf 2024
25 min
End the Pain: Rethinking CI for Large Monorepos
Scaling large codebases, especially monorepos, can be a nightmare on Continuous Integration (CI) systems. The current landscape of CI tools leans towards being machine-oriented, low-level, and demanding in terms of maintenance. What's worse, they're often disassociated from the developer's actual needs and workflow.Why is CI a stumbling block? Because current CI systems are jacks-of-all-trades, with no specific understanding of your codebase. They can't take advantage of the context they operate in to offer optimizations.In this talk, we'll explore the future of CI, designed specifically for large codebases and monorepos. Imagine a CI system that understands the structure of your workspace, dynamically parallelizes tasks across machines using historical data, and does all of this with a minimal, high-level configuration. Let's rethink CI, making it smarter, more efficient, and aligned with developer needs.
Atomic Deployment for JS Hipsters
DevOps.js Conf 2024DevOps.js Conf 2024
25 min
Atomic Deployment for JS Hipsters
Deploying an app is all but an easy process. You will encounter a lot of glitches and pain points to solve to have it working properly. The worst is: that now that you can deploy your app in production, how can't you also deploy all branches in the project to get access to live previews? And be able to do a fast-revert on-demand?Fortunately, the classic DevOps toolkit has all you need to achieve it without compromising your mental health. By expertly mixing Git, Unix tools, and API calls, and orchestrating all of them with JavaScript, you'll master the secret of safe atomic deployments.No more need to rely on commercial services: become the perfect tool master and netlifize your app right at home!

Workshops on related topic

React at Scale with Nx
React Summit 2023React Summit 2023
145 min
React at Scale with Nx
Top Content
Featured WorkshopFree
Isaac Mann
Isaac Mann
We're going to be using Nx and some its plugins to accelerate the development of this app.
Some of the things you'll learn:- Generating a pristine Nx workspace- Generating frontend React apps and backend APIs inside your workspace, with pre-configured proxies- Creating shared libs for re-using code- Generating new routed components with all the routes pre-configured by Nx and ready to go- How to organize code in a monorepo- Easily move libs around your folder structure- Creating Storybook stories and e2e Cypress tests for your components
Table of contents: - Lab 1 - Generate an empty workspace- Lab 2 - Generate a React app- Lab 3 - Executors- Lab 3.1 - Migrations- Lab 4 - Generate a component lib- Lab 5 - Generate a utility lib- Lab 6 - Generate a route lib- Lab 7 - Add an Express API- Lab 8 - Displaying a full game in the routed game-detail component- Lab 9 - Generate a type lib that the API and frontend can share- Lab 10 - Generate Storybook stories for the shared ui component- Lab 11 - E2E test the shared component
Node Monorepos with Nx
Node Congress 2023Node Congress 2023
160 min
Node Monorepos with Nx
Top Content
WorkshopFree
Isaac Mann
Isaac Mann
Multiple apis and multiple teams all in the same repository can cause a lot of headaches, but Nx has you covered. Learn to share code, maintain configuration files and coordinate changes in a monorepo that can scale as large as your organisation does. Nx allows you to bring structure to a repository with hundreds of contributors and eliminates the CI slowdowns that typically occur as the codebase grows.
Table of contents:- Lab 1 - Generate an empty workspace- Lab 2 - Generate a node api- Lab 3 - Executors- Lab 4 - Migrations- Lab 5 - Generate an auth library- Lab 6 - Generate a database library- Lab 7 - Add a node cli- Lab 8 - Module boundaries- Lab 9 - Plugins and Generators - Intro- Lab 10 - Plugins and Generators - Modifying files- Lab 11 - Setting up CI- Lab 12 - Distributed caching
Deploying React Native Apps in the Cloud
React Summit 2023React Summit 2023
88 min
Deploying React Native Apps in the Cloud
WorkshopFree
Cecelia Martinez
Cecelia Martinez
Deploying React Native apps manually on a local machine can be complex. The differences between Android and iOS require developers to use specific tools and processes for each platform, including hardware requirements for iOS. Manual deployments also make it difficult to manage signing credentials, environment configurations, track releases, and to collaborate as a team.
Appflow is the cloud mobile DevOps platform built by Ionic. Using a service like Appflow to build React Native apps not only provides access to powerful computing resources, it can simplify the deployment process by providing a centralized environment for managing and distributing your app to multiple platforms. This can save time and resources, enable collaboration, as well as improve the overall reliability and scalability of an app.
In this workshop, you’ll deploy a React Native application for delivery to Android and iOS test devices using Appflow. You’ll also learn the steps for publishing to Google Play and Apple App Stores. No previous experience with deploying native applications is required, and you’ll come away with a deeper understanding of the mobile deployment process and best practices for how to use a cloud mobile DevOps platform to ship quickly at scale.
MERN Stack Application Deployment in Kubernetes
DevOps.js Conf 2022DevOps.js Conf 2022
152 min
MERN Stack Application Deployment in Kubernetes
Workshop
Joel Lord
Joel Lord
Deploying and managing JavaScript applications in Kubernetes can get tricky. Especially when a database also has to be part of the deployment. MongoDB Atlas has made developers' lives much easier, however, how do you take a SaaS product and integrate it with your existing Kubernetes cluster? This is where the MongoDB Atlas Operator comes into play. In this workshop, the attendees will learn about how to create a MERN (MongoDB, Express, React, Node.js) application locally, and how to deploy everything into a Kubernetes cluster with the Atlas Operator.
Azure Static Web Apps (SWA) with Azure DevOps
DevOps.js Conf 2022DevOps.js Conf 2022
13 min
Azure Static Web Apps (SWA) with Azure DevOps
WorkshopFree
Juarez Barbosa Junior
Juarez Barbosa Junior
Azure Static Web Apps were launched earlier in 2021, and out of the box, they could integrate your existing repository and deploy your Static Web App from Azure DevOps. This workshop demonstrates how to publish an Azure Static Web App with Azure DevOps.