Introduction to the

Workspaces is an NPM term and feature for managing multiple packages under local root Package packages. (Yarn has long been supported, NPM has been supported in 7.x)

This feature makes it much easier to develop packages locally, especially when multiple packages are interdependent. Instead of manually executing the NPM link command, NPM install automatically creates symbolic links between valid workspaces and node_modules in the root directory.

A folder that can be created as a separate package with symbolic links is called a workspace, so there can be multiple workspaces, which can be configured in the workspaces field of package.json.

Configuration machine-specific

The WorkSpaces field accepts an array that can be filled with folder names relative to the root directory or with glob wildcards. Such as:

{
  "name": "my-workspaces-powered-project"."workspaces": [
    "workspace-a"]}Copy the code

The above configuration shows that under the root, there is a workspace -A folder that acts as an NPM package containing a package.json.

.
+-- package.json
`-- workspace-a
   `-- package.json
Copy the code

The desired effect is that the workspace-a folder will be symlinked to the node_modules folder in the root directory after the NPM install command is executed. The use and lookup of the package is no different from the normal installation of the package.

For this example, if NPM install is executed, the resulting directory structure looks like this:

. +-- node_modules | `-- workspace-a -> .. /workspace-a +-- package-lock.json +-- package.json `-- workspace-a `-- package.jsonCopy the code

Use workspaces

According to the package lookup rules defined by the NodeJS specification, any Workplace package that has a package.json file legally defined can be used to refer to the package through the name field defined in package.json.

In the example above, we can use the Workshop-A package as follows:

// ./workspace-a/index.js
module.exports = 'a'

// ./lib/index.js
const moduleA = require('workspace-a')
console.log(moduleA) // -> a
Copy the code

Perform:

node lib/index.js
Copy the code

In actual combat

Create a normal package development process folder, below which utils is treated as a separate package under the Packages /utils directory, with the entire Packages directory as our workspace. Screenshot below:

If you start the service, you can see the normal output:

Let’s take a look at the node_modules directory:

As you can see, it is very convenient to use workspace to develop multiple related packages without having to configure tsconfig, ESLint,rollup, etc. NPM natively supports Workspaces, which makes it easier to manage Mono-Repos.

Reference documentation

  • Doppelmutzi. Making. IO/monorepo – le…
  • Docs.npmjs.com/cli/v7/usin…