How to Publish Your First npm Package

Everything You Need to Know to Create a Useful, Accessible npm Package

Install npm

Choose a package name

Initialise your project

Initialise Git

git init
git add .
git commit -m "Initial commit"
git remote add origin remote repository URL
git push origin master

Take care to reference the right paths

__dirname vs ‘./’

A key exception

The path module

const path = require('path');const my_path = path.join(__dirname, 'my-dir', 'my-file.js');

Write the code

function log(msg){
console.log(msg);
};
module.exports = log;

Add Multiple Exports

function log(msg){
console.log(msg);
};
function shout(msg){
if (typeof msg === str) {
console.log(msg.toUpperCase())
} else {
log(msg)
};
};
function whisper(msg){
if (typeof msg === str) {
console.log(msg.toLowerCase())
} else {
log(msg)
};
};
module.exports = {log, shout, whisper};
const { log, shout, whisper } = require('my-module-name');

Add an Options Argument

function log(msg, options = { loudness: 'default' }){
if (options && options.loudness) {
switch (options.loudness) {
case 'shout':
if (typeof msg === str) console.log(msg.toUpperCase());
break;
case 'whisper':
if (typeof msg === str) console.log(msg.toLowerCase());
break;
default:
console.log(msg);
}
}
};
module.exports = log;
const log = require('my-module-name');log('Hello World', { loudness: 'shout' });

Write a great README

Test your package locally

Step 1:

Step 2:

Step 3:

Publish your package

Update your package

Version Control

npm version patch // 1.0.1
npm version minor // 1.1.0
npm version major // 2.0.0

Add badges

Writer and developer based in London. On Medium, I write about JavaScript and web development 💻

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store