DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 968,873 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for An extensive guide to build your NPM package and publish it.
Shreyas Pahune
Shreyas Pahune

Posted on

An extensive guide to build your NPM package and publish it.

Hey folks, I hope you all are doing great. I've been building APIs and backends using NodeJS and ExpressJS for a while now and the one thing that I find most tedious is setting up the project.

It includes:

  • Making directories like:
    • Middlewares
    • Routes
    • Database
    • Models
  • Setting up the boilerplate code in the index.js or the server.js file.
  • Making .env files and storing the secrets.
  • Installing usually used packages like:
    • CORS
    • ExpressJS
    • JWT
    • BcryptJS
    • DOTENV

We are going to make this whole process happen with just one command.

What are we going to build?

We are going to build a backend builder which lets us create the necessary folders, files and initialise the server with a basic get route. It will also install all the packages required for the server to work. So let's get started.

Step-1 : Making NPM Account

  • Make an account on NPM and login to the account.

Step-2 : Setting up the project

  • Make an empty directory/folder.
  • Create a js file named as bin.js in the folder.
  • Run npm init in that empty folder and set the entry point as bin.js.
  • This will create a package.json file.
  • Modify that file according to the below image.

package.json image

Step-3 : Coding

  • Inside the bin.js file import these three packages.
#!/usr/bin/env node

const process = require("process");
const fs = require("fs");
const child_process = require("child_process");
Enter fullscreen mode Exit fullscreen mode
  • We do not have to download these packages as they are inbuilt in NodeJS.
  • We use shebang code (#!/usr/bin/env node) to tell the kernel which interpreter should be used to run the file. You can simply ignore it.
  • When a user uses the package, they should get an intimation that some process is happening. So to do that add these two console.log() into the file.
// for user intimation
console.log("Building folders and initialising your server...⛳️");

console.log(
  "This might take few seconds...⏳"
);

Enter fullscreen mode Exit fullscreen mode
  • Now we have to create three folders:

    • db
    • routes
    • models
  • In order to do so we will use fs.mkdirSync(). mkdir means make directory and sync means it will make directory synchronously.

  • Add the below code to create folders.

// make folders
fs.mkdirSync(`${process.cwd()}/db`);
fs.mkdirSync(`${process.cwd()}/model`);
fs.mkdirSync(`${process.cwd()}/routes`);
Enter fullscreen mode Exit fullscreen mode
  • You might see that I have used process.cwd(). This means the folders would be created in the current working directory (cwd) in which our package or npx executable command would be used.

  • Now we have to install some packages so that our server could run.

  • We will install:

    • express
    • cors
    • jwt
    • dotenv
    • bcryptjs
    • nodemon (dev dependency)
  • If we want to run commands using a package we would have to use child_process.execSync().

  • child_process enables us to spawn subprocesses inside the main / parent process.

  • execSync lets us execute shell/terminal commands using nodejs.

  • Use the code given below for reference.


//  install packages
child_process.execSync("npm init -y", { stdio: [] });
child_process.execSync("npm install express", { stdio: [] });
child_process.execSync("npm install cors", { stdio: [] });
child_process.execSync("npm i jsonwebtoken", { stdio: [] });
child_process.execSync("npm i dotenv", { stdio: [] });
child_process.execSync("npm i bcryptjs", { stdio: [] });
child_process.execSync("npm i -D nodemon", { stdio: [] });


Enter fullscreen mode Exit fullscreen mode
  • Now we have to create a .env file to store secrets in it.
  • To make a file use a method fs.appendFileSync(). It adds the given data to the file and by any chance if the file is not present then it creates the file and writes the data in it.
fs.appendFileSync(`${process.cwd()}/.env`, `PORT=8080`);
Enter fullscreen mode Exit fullscreen mode
  • Now we have to make the server.js file and write some boilerplate code in it.
  • We will use the same function as above.
fs.appendFileSync(
  `${process.cwd()}/server.js`,
  `
const express = require('express');
const app = express();
require('dotenv').config();
const cors = require('cors');

// middlewares
app.use(cors());
app.use(express.json());

// defining port
const PORT = process.env.PORT || 3001;

// setting up an empty GET Route
app.get('/', (req, res)=>{res.json({message: "You've come to the right place... it's a GET request!!"})});

// Starting Server on PORT
app.listen(PORT, () => console.log('Server started on PORT Number: ' + PORT))
`
);

Enter fullscreen mode Exit fullscreen mode
  • The first argument in fs.appendFileSync() is the path to the file and the second argument is the data to be written in the file.

  • If we are going to push the data to a repository we will need a .gitignore file. So we will create that as well.

fs.appendFileSync(`${process.cwd()}/.gitignore`, 
`
node_modules 
.env
`);
Enter fullscreen mode Exit fullscreen mode
  • Now we will add a final intimation saying that everything is completed and you may use the project now.
console.log(
  "Folders are created and server.js is initialized with boilerplate code...\n RUN: nodemon server.js \nHappy Coding ✨"
);
Enter fullscreen mode Exit fullscreen mode

Step-4 : Publishing your NPM package

  • Navigate to the root directory of your project and run the following command.
npm publish --access=public
Enter fullscreen mode Exit fullscreen mode

To use the package, run npx @your_username/projectname@latest

Drum Roll πŸ₯!!

You have made your NPM package which handles the boring and tedious task of setting up a backend and you have published it as well. Thank you for reading the blog ✨.

View full Code:

Top comments (0)

Classic DEV Post from 2020:

js visualized

πŸš€βš™οΈ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! πŸ₯³

Happy coding!