DEV Community

Cover image for Create your own npm library
Daichi Izushi
Daichi Izushi

Posted on

Create your own npm library

Introduction

React.js, Three.js, and other excellent libraries that we usually use can actually be created by ourselves. I am posting this article as a review of a class on creating libraries at a college in Canada.

Prerequisites

Node.js must be available.
npm can be used by installing Node.js.

Publish your own library to npm

Project Setup

First, create an npm account.

Create a project directory in the local environment.

mkdir original-library
Enter fullscreen mode Exit fullscreen mode

Move to the project directory

cd original-library
Enter fullscreen mode Exit fullscreen mode

Initialize package.json file.

npm init -y
Enter fullscreen mode Exit fullscreen mode

This command creates package.json.

Log in to your npm account

Login to npm from the project directory and link the local repository to npm.

npm login
Enter fullscreen mode Exit fullscreen mode

Image description

When you hover over the password box, the character blindfolds you.
It reminded me of the manner in which the waiters turn their back when entering a password for a credit card transaction in a Japanese restaurant lol.
This character has manners.

Image description

After logging in with a browser, return to the terminal and check the linkage.

npm whoami
Enter fullscreen mode Exit fullscreen mode

If the npm registration name is output here, the login is complete.

Add necessary settings to package.json

Property Description

  1. name:
    The name of the package to be published to npm.

  2. version:
    The version number of the package. Conforms to semantic versioning.

  3. main:
    The file that serves as the entry point for the package. It is usually referenced when loading a package with require or import.
    Example: “main”: “index.js”

  4. keywords:
    keywords that are used to search for packages.
    An array of keywords to make it easier to search for packages is used by npm's search function.
    Example: “keywords”: [“library”, “example”].

  5. author:
    The author's information about the package. Can include name, email address, URL, etc.
    Example: “author”: “Your Name your.email@example.com (http://example.com)”

  6. license:
    Package license information.
    License information for the package. Use the identifier of the open-source license.
    Example: “license”: “ISC”

  7. description: A brief description of the package will be displayed in the npm package list and search results.
    Example: “description”: “A description of my library”

{
  "name": "@yourname/original-library",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": ""
}
Enter fullscreen mode Exit fullscreen mode

About the scope of name

How to add a scope
It appears that the scope name must be the same as the npm registration name. The format is @my-scope/package-name.
Usually, the team name, project name, or personal name is used.

Benefits of Scope

  1. Namespace Separation:
    Scopes can be used to avoid package name conflicts. Even if different organizations or projects have packages with the same name, they are distinguished by scope.

  2. Ease of Management:
    Ease of management: packages can be grouped by organization or team. This is especially useful when managing large projects or multiple projects.

  3. Access Control:
    Scope allows for access control.
    Scopes can be used to control the public scope of packages. Private scopes can be used to ensure that only specific users or teams have access.

Write the code for the library

Create an entry point file based on the index.js set in main and write the library code.

function sayHello() {
    return "Hello, World!";
}

function sum(a, b) {
  return a + b;
}

function multiply(a, b) {
  return a * b;
}

module.exports = {
  sayHello, sum, multiply
}
Enter fullscreen mode Exit fullscreen mode

Publish the library

Normally npm publish, but since scoped packages are treated as private by default, they must be published using the - access public option.

npm publish — access public
Enter fullscreen mode Exit fullscreen mode

Image description

New libraries have been added to npm packages.

Install your own library

Create a new project

mkdir call-function-from-original-library
cd call-function-from-original-library
Enter fullscreen mode Exit fullscreen mode

Copy the installation commands provided on the library details screen.

Image description

Install your own library in a new project

npm i @yourname/original-library
Enter fullscreen mode Exit fullscreen mode

When the above is performed, the following occurs

  1. Update node_modules directory:
    @yourname/original-library package is installed in node_modules directory.
    If there are already existing node_modules directories, new packages will be added to them.

  2. Updating package.json:
    @yourname/original-library is added to dependencies section of package.json file.
    If it already exists, the version is updated.

  3. Update package-lock.json:
    @yourname/original-library is added to the dependencies section of the package.json file.
    The package-lock.json file is updated to record the exact version of the installed package and its dependencies.
    This will allow other developers to install the same dependencies.

node_modules directory is excluded from Git tracking

node_modules directory contains many files, so managing it with Git would make the repository size too large.
Also, the presence of the package-lock.json file makes the dependency version fixed and removes it from Git tracking because other developers can reproduce the same environment.

touch .gitignore
Enter fullscreen mode Exit fullscreen mode

Add node_modules to .gitignore file

/node_modules
Enter fullscreen mode Exit fullscreen mode

Importing your own library

Add “type”: “module” to the created package.json.

{
  "dependencies": {
    "@yourname/original-library": "^1.0.0"
  },
  "type": "module"
}
Enter fullscreen mode Exit fullscreen mode

Create an index.js file to check if the library can be used correctly.
Import the library in the index.js file and call the functions.

import myLibrary from '@yourname/original-library';
const { sayHello, sum, multiply } = myLibrary;

console.log(sayHello());
console.log(sum(3, 4));
console.log(multiply(3, 4));
Enter fullscreen mode Exit fullscreen mode

Run index.js in a terminal

node index.js
Enter fullscreen mode Exit fullscreen mode

output

Hello, World!
7
12
Enter fullscreen mode Exit fullscreen mode

Updating your own library

This section describes the procedure when modifications are made to the library.

First, make modifications to the library

function sayHello() {
    return "Hello, World!";
}

function sum(a, b) {
  return a + b;
}

function multiply(a, b) {
  return a * b;
}

// add
function divide(a, b) {
  return a / b;
}

module.exports = {
  sayHello, sum, multiply, divide
}
Enter fullscreen mode Exit fullscreen mode

If you modify the library, you need to change the version in package.json. If the version is not changed, an error will occur when publishing.

  • MAJOR: Increased when backward incompatible changes are made.
  • MINOR: Increased when backward-compatible functionality is added.
  • PATCH: Increased when backward-compatible bug fixes are made.
{
  "name": "@yourname/original-library",
  "version": "1.0.1",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": ""
}
Enter fullscreen mode Exit fullscreen mode

Then log in to npm and publish.

npm login
npm publish --access public
Enter fullscreen mode Exit fullscreen mode

Image description

Verify that the library contents and version have been updated.

Conclusion

In this tutorial, we have gone through the process of creating and publishing your own npm library. From project setup to version control to public scoping, understanding how to create a library will enable you to contribute to the open source community and share your code with other developers.

Top comments (0)