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.

This talk has been presented at DevOps.js Conf 2022, check out the latest edition of this Tech Conference.

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
We will learn how to automate code and testing with GitHub Actions, including linting, formatting, testing, and deployments. Automating deployments with scripts and Git hooks can help avoid mistakes. Popular CI-CD frameworks like Jenkins offer powerful orchestration but can be challenging to work with. GitHub Actions are flexible and approachable, allowing for environment setup, testing, deployment, and custom actions. A custom AppleTools Eyes GitHub action simplifies visual testing. Other examples include automating content reminders for sharing old content and tutorials.
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
DevOps is a journey that varies for each company, and remote work makes transformation challenging. Pull requests can be frustrating and slow, but success stories like Mateo Colia's company show the benefits of deploying every day. Challenges with tools and vulnerabilities require careful consideration and prioritization. Investing in documentation and people is important for efficient workflows and team growth. Trust is more important than excessive control when deploying to production.
Why is CI so Damn Slow?
DevOps.js Conf 2022DevOps.js Conf 2022
27 min
Why is CI so Damn Slow?
Slow CI has a negative impact on productivity and finances. Debugging CI workflows and tool slowness is even worse. Dependencies impact CI and waiting for NPM or YARN is frustrating. The ideal CI job involves native programs for static jobs and lightweight environments for dynamic jobs. Improving formatter performance and linting is a priority. Performance optimization and fast tools are essential for CI and developers using slower hardware.
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
Today's Talk discusses rethinking CI in monorepos, with a focus on leveraging the implicit graph of project dependencies to optimize build times and manage complexity. The use of NX Replay and NX Agents is highlighted as a way to enhance CI efficiency by caching previous computations and distributing tasks across multiple machines. Fine-grained distribution and flakiness detection are discussed as methods to improve distribution efficiency and ensure a clean setup. Enabling distribution with NX Agents simplifies the setup process, and NX Cloud offers dynamic scaling and cost reduction. Overall, the Talk explores strategies to improve the scalability and efficiency of CI pipelines in monorepos.
The Zen of Yarn
DevOps.js Conf 2022DevOps.js Conf 2022
31 min
The Zen of Yarn
Let's talk about React and TypeScript, Yarn's philosophy and long-term relevance, stability and error handling in Yarn, Yarn's behavior and open source sustainability, investing in maintenance and future contributors, contributing to the JavaScript ecosystem, open-source contribution experience, maintaining naming consistency in large projects, version consistency and strictness in Yarn, and Yarn 4 experiments for performance improvement.
Atomic Deployment for JS Hipsters
DevOps.js Conf 2024DevOps.js Conf 2024
25 min
Atomic Deployment for JS Hipsters
This Talk discusses atomic deployment for JavaScript and TypeScript, focusing on automated deployment processes, Git hooks, and using hard links to copy changes. The speaker demonstrates setting up a bare repository, configuring deployment variables, and using the post-receive hook to push changes to production. They also cover environment setup, branch configuration, and the build process. The Talk concludes with tips on real use cases, webhooks, and wrapping the deployment process.

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.