npm is package manager for Node.js that allows JavaScript developers to easily share packaged modules of code. In this tutorial we’ll be creating and publishing a simple npm package that displays a funny quote in the console.
Before you can publish a package you’ll need an npm account (sign up here).
With the account created login by running the following command:
npm login
Enter your account details when prompted to login.
Next let’s create a folder for our package and a package.json
file:
mkdir funny-quotes
cd funny-quotes
touch package.json
Code language: plaintext (plaintext)
Open the package.json
file in your code editor of choice and add the following:
{
"name": "funny-quotes",
"version": "0.1.0",
"main": "index.js",
"license": "MIT",
"description": "Funny quotes in your console.",
"keywords": [
"funny",
"quote",
"console"
]
}
Code language: JSON / JSON with Comments (json)
Name and version are required the others are optional.
- name – unique package name.
- version – current release version of the package.
- main – entry point for the package.
- licence – we’ll use MIT which allows developers to do anything they wish with the code.
- description – short description of what the package does.
- keywords – a list of keywords to help people discover your package.
We can now create the main entry point for the package:
touch index.js
Code language: plaintext (plaintext)
And add the following code:
const quotes = [
'"I’m sick of following my dreams, man. I’m just going to ask where they’re going and hook up with em later." — Mitch Hedberg',
'"Before you marry a person, you should first make them use a computer with slow Internet to see who they really are." - Will Ferrell',
'"Someone asked me, if I were stranded on a desert island what book would I bring: ‘How to Build a Boat.’" - Steven Wright',
];
const randomQuote = quotes[Math.floor(Math.random() * quotes.length)];
console.log(
"\x1b[33m%s\x1b[0m",
"---------------------\n" + randomQuote + "\n---------------------"
);
Code language: JavaScript (javascript)
This create’s an array with some quotes and then grabs a random quote to display. \x1b[33m
is an escape sequence that when encountered switches the color of the text logged to yellow so the quote will stand out a little, \x1b[0m
then resets the color.
Let’s test the script by running the following command:
node index.js
Code language: plaintext (plaintext)
You should see a random quotes output in the console.
With everything working we can go ahead and publish the package:
npm publish
If there was no errors you’ll get an email letting you know the package was successfully published. If you visit the npm website and search for the package by name it will now appear in the search results.
The package can now be installed from npm using the following command:
npm i funny-quotes