Imagine that we’ve a project that has been initialized with
As we all know, each npm package has a unique name in the npm registry:
In case that package’s name exists, we couldn’t publish the package. Well, our options here are limited. We can rename it, but we don’t ought to.
Guess what we’re going to do now 😉
What are Scoped Packages?
Scoped Packages is a way to group related npm packages together, much like namespaces. This packages group is connected by a “scope” and in fact - it’s perfect for organizations and users.
Scoped packages provides a few advantages:
- We don’t have to worry if the name exists - just name it.
- We don’t have to worry that someone else will publish into our scope - only scope members have the permission.
- We don’t have to switch the npm registry in order to install and publish the packages - we assign a specific registry for the scope.
How to Initialize
When we create a package, we can use
npm init --scope=sample-scope.
This command creates a package.json file and names the package with the provided scope:
Notice that the scope name begins with
@ and followed by a slash.
Note: In case the package has already been initialized - we just have to change its name.
How to Publish & Install
Now that we have an initialized scoped package, we’d like to communicate with a npm registry in order to publish and install this package.
There are two options for choosing a registry:
- The official public.
- A private one.
To assign the scope with a private registry, use:
npm config set @sample-scope:registry http://sample-registry.com
Notice that packages which aren’t part of the scope - will be resolved from the default registry.
Now, let’s communicate with the registry, and at first - we’ll publish the package:
npm publish --access public
Note: Scoped packages are private by default. You cannot publish privately into the official registry unless you have a paid account or a private registry.
On top of that, installing our package inside another project is performed by:
npm install @sample-scope/sample-package
Today we explored the scoped packages in npm and focused on its benefits. We learned to associate a registry with the scope, publish a package and install it on another one.
Remember - scope packages are might be suitable for your organization. 😎