How to build and publish your npm package.

The first step of creating npm will be creating a git repository on github.

So this empty repository was created:

https://github.com/webgirlkristina/sleepjs.git

Now we can download our repository.

git clone https://github.com/webgirlkristina/sleepjs.git webgirlkristina-sleep
cd webgirlkristina-sleep

Create file .gitignore

node_modules/

Now we can start our npm project.

npm init -y

Let's open and edit the config file package.json.

The git repository was already there, we only added description and changed the file name to - sleep.js

{
  "name": "webgirlkristina-sleep",
  "version": "1.0.0",
  "description": "sleep function for JavaScript",
  "main": "sleep.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/webgirlkristina/sleepjs.git"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/webgirlkristina/sleepjs/issues"
  },
  "homepage": "https://github.com/webgirlkristina/sleepjs#readme"
}

Now we can build our JavaScript package. For this example, we build a JS function similar to PHP function sleep.

File - sleep.js

const sleep = (sec) => new Promise(resolve => setTimeout(resolve, sec * 1000));
module.exports = sleep;

In order to let other people use our package, we need to create instructions. Let's edit file README.md

# Sleep
Function `sleep` for JavaScript. 
>sleep(seconds) -> Promise
## Installation

    npm i webgirlkristina-sleep

## Usage

```js
const sleep = require('webgirlkristina-sleep');
const test = async () => {
	console.log('text1');
	await sleep(2); //sleep for 2 seconds
	console.log('text2');
};
test();
```

This is the Markdown format and on github this looks like:

Example of README.MD on GitHub

Now we can push our package to GitHub, but first let's check git user.

git config user.name
How to check current git user.

We can set user data for git this way:

git config --global user.name "webgirlkristina"
git config --global user.email "webgirlkristina@gmail.com"

And our first commit.

git add .
git commit -m "first"

Don't forget to add the package version.

git tag -a v1.0 -m "the first version"

Everything is ready to push on GitHub

git push --follow-tags

Now we can publish our package on npmjs.com. But first we need to login npm login. You can check current login: npm whoami.

And finally:

npm publish

Now our package is available to anybody.

To test our new package we create a new NPM project. And install our package:

npm i webgirlkristina-sleep

Our test script:

const sleep = require('webgirlkristina-sleep');

const test = async () => {
	console.log('text1');
	await sleep(2); //sleep for 2 seconds
	console.log('text2');
};
test();

That's it, our package working.

Login to post a comment.