How to Create and Publish Your First Private NPM Package

Written by yuraabharian | Published 2022/07/09
Tech Story Tags: git-workflow | programming | npm | npm-package | npm-and-nodejs | debugging | hackernoon-top-story | testing

TLDRIn this article, I want to show how we can easily create our first private npm package. With private npm packages, you can host code that is only visible to you and those with access. We’ll talk more about it. We are going to create and publish a private package on GitHub so make sure you have got acquainted with prerequisites before starting this article. We'll talk about how to use GitHub Actions to manage and use private code alongside public code.via the TL;DR App

In this article, I want to show how we can easily create our first private npm package.

We are going to create and publish a private package on GitHub, so make sure you have got acquainted with prerequisites before starting this article. So let’s get started.

Prerequisites:

What is private npm packages and where it can be used?

  • With private npm packages, you can host code that is only visible to you and those with access, allowing you to manage and use private code alongside public code in your projects.

Project Structure

math-lib/
--.github/
  --workflows/
    --main.yml
--build/ this is autogenerated folder
--src/
  --app.ts
--types/
  --index.d.ts
--.gitignore
--package.json
--tsconfig.json

Part 1: Building a Private npm Package

Step 1: Init a Node.js project with TypeScript.

Note: You can learn how to do this by following this article How to Setup a Node Express with TypeScript or you can just clone this repo https://github.com/YuraAbharian/node-express-typescript

Step 2: Now let’s create GitHub Actions workflows.

Let’s add some configurations:

name: Node.js Private Package

on: 
  push: 
      branches: 
        - master

jobs: 
  publish-gpr:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v2
      - uses: actions/setup-node@v2
        with:
          node-version: '14.x'
          registry-url: 'https://npm.pkg.github.com/'
      - run: npm install
      - run: npm run build
      - run: npm publish
        env:
          NODE_AUTH_TOKEN: ${{secrets.GITHUB_TOKEN}}

Note: Remember GITHUB_TOKEN, we’ll talk more about it a bit later

Step 3: Let’s create/update the src/app.ts file

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

export function minus(a: number, b: number): number {
    return a - b;
}

export function divide(a: number, b: number): number {
    return a / b;
}

export function multiple(a: number, b: number): number {
    return a * b;
}

Step 4: Now we need to declare a module for our package

  • Create a types directory at the root of your project

  • Create an index.d.ts file in the types directory

Add declare types for this module

declare module "@GITHUB_USERNAME/PACKAGE_NAME" {
    function sum(a: number, b: number): number;
    function minus(a: number, b: number): number;
    function divide(a: number, b: number): number;
    function multiple(a: number, b: number): number;
}

Note:

- GITHUB_USERNAME it is your github username

- PACKAGE_NAME it is your private package name

Example: "@yuraabharian/math-lib"

Step 5: Let’s work on package.json file

{
  "name": "@GITHUB_USERNAME/PACKAGE_NAME",
  "version": "1.0.0",
  "description": "",
  "main": "./build/app.js",
  "author": "",
  "license": "ISC",
  "types": "./types/index.d.ts",
  "publishConfig": {
    "registry": "https://npm.pkg.github.com/"
  },
  "repository": {
    "url": "git://github.com/GITHUB_USERNAME/PACKAGE_NAME.git"
  },
  "scripts": {
    "build": "npx tsc"
  },
  "devDependencies": {
    "@types/node": "^18.0.0",
    "typescript": "^4.7.4"
  }
}

Example: git://github.com/yuraabharian/math-lib.git (this will be a link to you GitHub repository)

Note: These @GITHUB_USERNAME/PACKAGE_NAME fieds are the same as in Step 4

Step 6: Let’s configure our repository environment before pushing the code

  • In the Step 2 I asked you to remember GITHUB_TOKEN because this variable is very important.

  • Go to GitHub Repository - Settings

Step 7: Then Go to Secrets

Step 8: Open Actions

  • Click New repository secret

Required: Follow by this link https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token to generate a new token.

Note: Save the GITHUB_TOKEN elsewhere because we'll need them in Part 2 of this article.

Note: Give only write:packages access for this token

Step 9: Now let’s push our code to GitHub

Step 10: Open the Repository → Actions and you should see that your package has been deployed

Step 11: To find your package, go to your GitHub profile → Packages

Conclusion of the first part: at this point you should see your package deployed

In the second part of this article, we will learn how to install a private package because it requires some actions, besides npm install package.

Part 2: Installation and Testing

Step 1: Set up Node.js project

Note: You can see how to do that in Part 1 → Step 1

Step 2: Then at the root of the project intsall your package. The link to your package you can take by GitHub profile → Packages → math-lib (this is your package name)

Step 3: Now go to src/app.ts file and update it

import express, {Application, Request, Response} from 'express';
import {sum, minus, multiple, divide} from '@yuraabharian/math-lib';

const app: Application = express();

const PORT: number = 3001;

app.use('/sum', (req: Request, res: Response): void => {
    res.send(`RESULT: ${sum(5, 2)}`, );
});

app.use('/minus', (req: Request, res: Response): void => {
    res.send(`RESULT: ${minus(2, 2)}`);
});

app.use('/multiple', (req: Request, res: Response): void => {
    res.send(`RESULT: ${multiple(12, 2)}`);
});

app.use('/divide', (req: Request, res: Response): void => {
    res.send(`RESULT: ${divide(10, 2)}`);
});

app.listen(PORT, (): void => {
    console.log('SERVER IS UP ON PORT:', PORT);
});

Note: Keep in mind that I'm importing math-lib from my @yuraabharian/math-lib repository to make your template look like @GITHUB_USERNAME/PACKAGE_NAME

Step 4: Run your project npm start

node-express-typescript % npm start

> express-typescript@1.0.0 start
> npx tsc && node build/app.js

SERVER IS UP ON PORT: 3001

Step 5: Go to your browser and open http://localhost:3001/sum

This works, so now let's test all the methods:

Summary: In this article, we created and tested your first private npm package, I hope you enjoyed my article. If you have any questions, you can contact me via email, LinkedIn or in the comments. Best wishes


Written by yuraabharian | I am a Senior Software Engineer. If you have any questions, you can contact me via yuraabharian@gmail.com or LinkedIn
Published by HackerNoon on 2022/07/09