WittCode💻

Create and Publish an npm Package

By

Create and publish a package to npm, learn what a scoped npm package is, how to publish a scoped package to npm, and how to search npm for a specific package.

Table of Contents 📖

What is npm?

Node package manager, or npm, is a software package manager, registry, and installer for JavaScript. Npm allows developers to use and share JavaScript code.

Creating and using an npm Account

We need an npm account to publish a package to npm. An npm account can be created by using the following URL.

https://www.npmjs.com/signup

Now we need to log in to our npm account through the command line by using the command npm login.

npm login

After entering in the correct information, output should be similar to below.

Logged in as <username> on https://registry.npmjs.org/.

Creating an npm Package

After we have logged into npm, lets create a package to publish. Create a directory to place the desired package in. For this article, the package we will be publishing is a simple script that subscribes a user to the YouTube channel WittCode. The directory will be called yt-subscribe.

mkdir yt-subscribe

Image

Now, to make this folder an npm package, we use the npm init command.

npm init

The command npm init sets up a new npm package. Specifically, it create a package.json file. The package.json file contains important metadata about an npm project such as the name, version, along with its dependencies, development dependencies, and other important information. Fill out the information the npm init command prompts for.

package name: (yt-subscribe) 
version: (1.0.0) 
description: Subscribes a user to the WittCode YouTube channel
entry point: (index.js) 
test command: 
git repository: https://github.com/WittCode/yt-subscribe
keywords: ["youtube", "wittcode", "amazing"]
author: WittCode
license: (ISC) MIT

package.json Explanation

The package name and version fields are required to publish a package to npm. Specifically, the package name is what the package will be called on npm. The description and keywords fields help others find the package in npm. Entry point is the primary entry point into the package. In other words, whatever is exported from the entry point is what will be returned when calling require('package-name').

// require() returns whatever is exported
// from the file listed as entry point in package.json
const ytSubscribe = require('yt-subscribe');

Test command is a command that is run whenever npm test is called. Author is the author of the package. Git repository is the git repository associated with the package. License lets other users know the permissions/restrictions on using this package.

Adding Code to the Package

Now, lets create an index.js file and add some code to it. This code will export a function that will subscribe the user to WittCode, if they pass some screen resolution checks. First create an index.js file.

Then install a few dependencies that this program will rely on.

npm install open
npm install robotjs

Both of these packages can be downloaded from npm as they have been published to it, just like we will do with this package. Now, add the following code to index.js.

const robot = require('robotjs');
const open = require('open');

module.exports = () => {

    const screenSize = robot.getScreenSize();

    // Works with correct dimensions
    if (screenSize.width === 1920 && screenSize.height === 1080) {
        subscribeToWittCode();
    } else {
        console.log("Dimensions won't work with application: must be 1920x1080.");
    }

    async function subscribeToWittCode() {

        await open('https://www.youtube.com');

        setTimeout(() => {
            // F11 makes browser window full screen
            robot.keyTap('f11');
            // Pressing / in YouTube goes to search bar
            robot.keyTap('/');
            robot.typeString('WittCode');
            robot.keyTap('enter');
            
            setTimeout(() => {
                robot.moveMouse(1600, 200);
                robot.mouseClick();
            }, 3000);

        }, 3000);

    }

}

All this code does is import a few libraries and use them to open a browser, navigate the cursor a certain location, type in some text, and then click. The functionality doesn't really matter, but exporting this code from the file is important as it is what will be exported when require('yt-subscribe') is called. For example, one could capture and call the exported function like so.

const subscribeToWittCode = require('yt-subscribe');
subscribeToWittCode();

Publishing the Package

Now, we just need to publish our package with npm publish.

npm publish

The output should be similar to the following.

npm notice 
npm notice 📦  yt-subscribe@1.0.0
npm notice === Tarball Contents === 
npm notice 918B index.js    
npm notice 599B package.json
npm notice === Tarball Details === 
npm notice name:          yt-subscribe                            
npm notice version:       1.0.0                                   
npm notice package size:  811 B                                   
npm notice unpacked size: 1.5 kB                                  
npm notice shasum:        ...
npm notice integrity:     ...
npm notice total files:   2                                       
npm notice 
+ yt-subscribe@1.0.0

The npm publish command publishes a package to the npm registry. If a package with the same name already exists on npm then we will receive an error and won't be able to publish it. To fix this, just use a different name in package.json.

Verifying the Package was Published

We can verify if the package was published by using the npm search command and providing it the package name.

npm search yt-subscribe

This should give the following output.

NAME           | DESCRIPTION          | AUTHOR          | DATE       | VERSION  
yt-subscribe   | Subscribe to a…      | =wittcode       | 2022-06-08 | 1.0.0 

Requiring the Package

Now, lets create another npm project and require the package we created.

mkdir package-test
cd package-test
npm init -y
npm install yt-subscribe

First we create a directory called package-test, we then navigate into it, initialize it as an npm project using the defaults for package.json (provided by -y), and then install the package we made. Now, create an index.js file, require our package, and then run the function.

const subscribeToWittCode = require('yt-subscribe');
subscribeToWittCode();

Finally, run the index.js file to see the program in action.

node index.js

Scoped Packages

All npm packages have a name, but some may also have a scope. A scope is simply a string prepended to the package name that is usually used to indicate ownership. Specifically, it goes after a @ and before a /. For example, we could add the scope wittcode to our package by making the name property in package.json the following.

@wittcode/yt-subscribe

Scopes are used to group related packages together, but can also assure that we can use any package name we want without fear of it already being taken. For example, if the package name yt-subscribe was already taken, we could use @wittcode/yt-subscribe instead.

Publishing a User Scope

To publish to a user scope, we can change the name in package.json to include our user scope. Change the name key in package.json to the following.

"name": "@wittcode/yt-subscribe"

Now, just republish the npm package by using npm publish.

npm publish

Upon doing this the following error will be displayed.

npm ERR! code E402
npm ERR! 402 Payment Required - PUT https://registry.npmjs.org/@wittcode%2fyt-subscribe - You must sign up for private packages

This is because publishing a scoped package, by default, makes the package private. However, to use a private package (meaning it is only visible to the user and chosen collaborators) we need a paid user or organization account. To be allowed to make private packages, the following link can be used.

https://www.npmjs.com/products

However, we can publish a scoped package publicly by tagging on "--access=public" to the npm publish command.

npm publish --access=public

Now if we run an npm search for yt-subscribe we will get the following.

NAME                      | DESCRIPTION          | AUTHOR          | DATE       | VERSION  | KEYWORDS
yt-subscribe              | Subscribe to a…      | =wittcode       | 2022-06-08 | 1.0.0    | youtube 
@wittcode/yt-subscribe    | Subscribe to a…      | =wittcode       | 2022-06-08 | 1.0.0    | youtube

We can also make the package a scoped package by tagging on --scope= to npm init. For example, when we created this package, if we wanted the package name to be scoped to wittcode, we would do the following.

npm init --scope=wittcode

This tells npm to prepend @wittcode to the package name when creating the package.json file.

Searching for all Scoped Packages

If we want to search for all the packages listed under a certain scope, we can use npm search . For example, to search for all npm packages of the wittcode scope we would issue the following command.

npm search @wittcode

This says find all npm packages that have the string @wittcode in their package name.

How Scoped Packages are Installed

When we run npm install, the required packages listed in package.json are installed and placed inside node_modules. However, when we install a scoped package, the package is installed inside the scope subdirectory. Therefore, if we require a scope package, we also have to specify the scope.

const subscribeToWittCode = require('@wittcode/yt-subscribe');

Summary

But there we have it! Sharing code for the world to see is not only cool but can also be very helpful to other programmers. If this article was helpful, please consider donating by using the link at the top of the page, sharing this article, and subscribing to my YouTube channel WittCode.