46

Build & Publish a Node Package Module (NPM)

 5 years ago
source link: https://www.tuicool.com/articles/hit/IVFZjmB
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

In this post, we are going to build and publish a Node Package Module (NPM). The module we are going to build is a simple utility which will take a  Web supported color name as an argument and spits out the HEX & RGB values for the same. We are going to use a Test Driven Development (TDD) style of coding for building this module.

I have taken the color names from htmlcolorcodes.com – Thanks to them!

Before we get started, here is a quick preview of the CLI version in action

The story behind rebeccapurple . RIP Rebecca Meyer.

Getting Started

Below are the steps we are going to follow

  1. Setup Yeoman
  2. Install Generator
  3. TDD Colorcode
  4. Validate Code Coverage
  5. Push to Github
  6. Setup Travis CI
  7. Setup Coverall
  8. Publish to NPM

Setup Yeoman

If you are new to Yeoman, Yeoman is

vIFVv2u.png!web

What is Yeoman?

Ripping off from yeoman.io

Yeoman helps you to kickstart new projects, prescribing best practices and tools to help you stay productive.

To do so, we provide a generator ecosystem. A generator is basically a plugin that can be run with the yo command to scaffold complete projects or useful parts.

Through our official Generators, we promote the “Yeoman workflow”. This workflow is a robust and opinionated client-side stack, comprising tools and frameworks that can help developers quickly build beautiful web applications. We take care of providing everything needed to get started without any of the normal headaches associated with a manual setup.

With a modular architecture that can scale out of the box, we leverage the success and lessons learned from several open-source communities to ensure the stack developers use is as intelligent as possible.

As firm believers in good documentation and well thought out build processes, Yeoman includes support for linting, testing, minification and much more, so developers can focus on solutions rather than worrying about the little things.

So ya, Yeoman is like your File > New > NPM project | fill the project information and boom! A NPM project gets generated; but from command line.

To install Yeoman globally, run

➜  ~ npm install yo --global

And to validate, run

➜  ~ yo --version
2.0.3

Install Node.js

Before we go further, make sure you have Node.js installed on your machine. You can follow this postHello Nodefor same. I am using the following versions

➜  ~ node -v
v8.11.1
➜  ~ npm -v                     
5.6.0

generator-np

In this post, we are going to use a Yeoman generator named generator-np to scaffold our base for building the NPM. To install the generator globally, run

➜  ~ npm install generator-np --global

Once the installation is done, we are good to scaffold our app

Scaffold color2code

Anywhere on your machine, create a folder named color2code and open a new terminal/prompt there. Now, run

➜  color2code yo np

And you can answer the questions as shown below

u2a6Zf3.png!web This will take a moment to complete scaffolding.

Once the project scaffolded, we should see something like

.
├── README.md
├── cli.js
├── lib
│   └── index.js
├── package.json
├── src
│   ├── cli.js
│   └── lib
│       └── index.js
└── test
    └── index.js

In this project, we are going to follow a Test Driven Development approach. We will first update the test / index . js file with all possible scenarios and then get started with the code.

Next, we are going to work in src folder to update the cli . js and the  lib / index . js files.

Before we get started, let’s quickly look at the solution.

Color2Code Solution

The app we are going to build is a simple utility that takes a popular web supported color names and spits out the RGB and HEX values of the same.

We are going to maintain a collection of all the web supported colors and their HEX values. And in our code, we are going to read color name and fetch the HEX value. We then use the HEX value to generate the RGB version of the same.

Sounds simple right?

So, let’s see how to work with this solution & build a NPM.

Update project configuration

I have made a few changes to the project so that things are a bit more easy to manage.

Open . eslintrc and make the changes to the properties shown below

{
    // snipp snipp
    "no-magic-numbers": [0],
    // snipp snipp
    "eol-last": [0],
    // snipp snipp
    "lines-around-comment": [2, {
      "beforeBlockComment": false
    }],
    // snipp snipp
    "newline-after-var": [0],
    // snipp snipp
    "space-before-function-paren": [2, {
      "anonymous": "never",
      "named": "never"
    }],
    // snipp snipp
}

Next, we are going to update package . json as highlighted below

{
  "name": "color2code",
  "version": "0.1.0",
  "description": "Get color code from color name",
  "bin": "cli.js",
  "main": "lib/index.js",
  "files": [
    "lib/",
    "cli.js"
  ],
  "keywords": [
    "color code", "color name", "rgb", "hex", "CLI", "converter"
  ],
  "license": "MIT",
  "repository": {
    "type": "git",
    "url": "https://github.com/arvindr21/color2code"
  },
  "scripts": {
    "audit": "nsp check package",
    "build": "babel -d ./ ./src --copy-files",
    "check": "npm run audit && npm outdated --depth 0",
    "coverage": "nyc --reporter=lcov --reporter=text --reporter=html npm test",
    "coveralls": "npm run coverage && cat ./coverage/lcov.info | coveralls && rm -rf ./coverage",
    "lint": "eslint src test",
    "test": "ava --require babel-core/register --verbose",
    "validate": "npm run lint && npm test",
    "prepare": "npm run build && npm run validate",
    "pp": "npm run prepare",
    "major": "pmm major",
    "minor": "pmm minor",
    "patch": "pmm patch"
  },
  "author": {
    "name": "Arvind Ravulavaru",
    "email": "[email protected]",
    "url": "https://thejackalofjavascript.com"
  },
  "pre-commit": [
    "validate"
  ],
  "dependencies": {
    "meow": "^3.7.0",
    "chalk": "^1.1.1"
  },
  "devDependencies": {
    "ava": "^0.14.0",
    "babel-cli": "^6.5.1",
    "babel-core": "^6.5.2",
    "babel-eslint": "^6.0.0",
    "babel-plugin-transform-function-bind": "^6.5.2",
    "babel-preset-es2015": "^6.5.0",
    "coveralls": "^2.11.9",
    "eslint": "^2.5.1",
    "nsp": "^2.2.0",
    "nyc": "^6.1.1",
    "pmm": "^1.3.0",
    "pre-commit": "^1.1.2"
  }
}

Finally, update . travis . yml as shown below

language: node_js
node_js:
  - "4"
  - "5"
  - "6"
  - "7"
  - "8"
  - "9"
  - "10"
install:
  - npm install
script:
  - npm run audit
  - npm run build
  - npm run validate
after_success:
  - npm run coveralls

That is all!

Test Driven Development – TDD

To work with the code base we have just scaffolded, we are going to use TDD or Test Driven Development. We are going to write the test cases first and then develop our code.

TDD is not for the weak hearted. Seeing your application fail even before writing a single line of code takes courage.

You can read more about TDD here: Test Driven Development by Example

Write Test Cases

To get started, we are going to write the test cases first and see our app fail and then start making the required changes to our code to fix it.

Open test / index . js and update it as shown below

import test from 'ava';
import 'babel-core/register';
 
import color2code from '../src/lib/';
 
const invalidColor = 'reed';
const invalidColors1 = 'reed green';
const invalidColors2 = 'green reed';
const testColor = 'red';
const multiColors = 'red green';
const invalidColorMSG = 'Sorry, this dosen\'t seem to be a valid Web color name';
const noColorMSG = 'Please provide a color name and try again.';
 
const expRedResult = {
  name: 'red',
  hex: '#f00',
  rgb: 'rgb(255, 0, 0)'
};
const expGreenResult = {
  name: 'green',
  hex: '#008000',
  rgb: 'rgb(0, 128, 0)'
};
 
test('color2code: no color name', (t) => {
  t.is(color2code(), noColorMSG);
});
 
test('color2code: color name', (t) => {
  t.is(color2code(testColor).name, testColor);
});
 
test('color2code: HEX value', (t) => {
  t.is(color2code(testColor).hex, expRedResult.hex);
});
 
test('color2code: RGB value', (t) => {
  t.is(color2code(testColor).rgb, expRedResult.rgb);
});
 
test('color2code: multiColors', (t) => {
  t.is(color2code(multiColors).length, multiColors.split(' ').length);
});
 
test('color2code: multiColors check red hex value', (t) => {
  t.is(color2code(multiColors)[0].hex, expRedResult.hex);
});
 
test('color2code: multiColors check green hex value', (t) => {
  t.is(color2code(multiColors)[1].hex, expGreenResult.hex);
});
 
test('color2code: multiColors check red rgb value', (t) => {
  t.is(color2code(multiColors)[0].rgb, expRedResult.rgb);
});
 
test('color2code: multiColors check green rgb', (t) => {
  t.is(color2code(multiColors)[1].rgb, expGreenResult.rgb);
});
 
test('color2code: invalid color name', (t) => {
  t.is(color2code(invalidColor), invalidColorMSG);
});
 
test('color2code: invalid color name multiple order 1', (t) => {
  t.is(color2code(invalidColors1), invalidColorMSG);
});
 
test('color2code: invalid color name multiple order 2', (t) => {
  t.is(color2code(invalidColors2), invalidColorMSG);
});

The above file outlines 5 scenarios

  1. If there is no color name provided to our NPM
  2. If one color name is provided to our NPM
  3. If more than one color names are provided to our NPM
  4. If an invalid color name is provided to our NPM
  5. If an invalid color name is provided along with valid color names to our NPM

The code we are writing should satisfy the above 5 scenarios.

Now, let’s run the NPM and see it fail.

Run the NPM

We are going to use nodemon to watch our app for changes and rebuild our application.

To install nodemon, run

➜ ~ npm install nodemon --global

Once nodemon is installed, from inside color2code folder, run

➜  color2code ✗ nodemon --watch ./src --watch ./test  --exec npm run pp

If the command ran successfully, we should see an error blob stating that tests have failed.

Yay! we did it.

Now, let’s get cracking on fixing these cases.

PS: Keep the nodemon running in the terminal/prompt. As we keep making changes and saving files, the tests will be executed again.

Develop the NPM

First, we are going to get a dump of Web colors. Thanks to htmlcolorcodes.com , we have list of 148 color names.

Create a file named colors . json inside  src / lib folder and update it as shown below

{
    "aliceblue": "f0f8ff",
    "antiquewhite": "faebd7",
    "aqua": "0ff",
    "aquamarine": "7fffd4",
    "azure": "f0ffff",
    "beige": "f5f5dc",
    "bisque": "ffe4c4",
    "black": "000",
    "blanchedalmond": "ffebcd",
    "blue": "00f",
    "blueviolet": "8a2be2",
    "brown": "a52a2a",
    "burlywood": "deb887",
    "cadetblue": "5f9ea0",
    "chartreuse": "7fff00",
    "chocolate": "d2691e",
    "coral": "ff7f50",
    "cornflowerblue": "6495ed",
    "cornsilk": "fff8dc",
    "crimson": "dc143c",
    "cyan": "0ff",
    "darkblue": "00008b",
    "darkcyan": "008b8b",
    "darkgoldenrod": "b8860b",
    "darkgray": "a9a9a9",
    "darkgrey": "a9a9a9",
    "darkgreen": "006400",
    "darkkhaki": "bdb76b",
    "darkmagenta": "8b008b",
    "darkolivegreen": "556b2f",
    "darkorange": "ff8c00",
    "darkorchid": "9932cc",
    "darkred": "8b0000",
    "darksalmon": "e9967a",
    "darkseagreen": "8fbc8f",
    "darkslateblue": "483d8b",
    "darkslategray": "2f4f4f",
    "darkslategrey": "2f4f4f",
    "darkturquoise": "00ced1",
    "darkviolet": "9400d3",
    "deeppink": "ff1493",
    "deepskyblue": "00bfff",
    "dimgray": "696969",
    "dimgrey": "696969",
    "dodgerblue": "1e90ff",
    "firebrick": "b22222",
    "floralwhite": "fffaf0",
    "forestgreen": "228b22",
    "fuchsia": "f0f",
    "gainsboro": "dcdcdc",
    "ghostwhite": "f8f8ff",
    "gold": "ffd700",
    "goldenrod": "daa520",
    "gray": "808080",
    "grey": "808080",
    "green": "008000",
    "greenyellow": "adff2f",
    "honeydew": "f0fff0",
    "hotpink": "ff69b4",
    "indianred": "cd5c5c",
    "indigo": "4b0082",
    "ivory": "fffff0",
    "khaki": "f0e68c",
    "lavender": "e6e6fa",
    "lavenderblush": "fff0f5",
    "lawngreen": "7cfc00",
    "lemonchiffon": "fffacd",
    "lightblue": "add8e6",
    "lightcoral": "f08080",
    "lightcyan": "e0ffff",
    "lightgoldenrodyellow": "fafad2",
    "lightgray": "d3d3d3",
    "lightgrey": "d3d3d3",
    "lightgreen": "90ee90",
    "lightpink": "ffb6c1",
    "lightsalmon": "ffa07a",
    "lightseagreen": "20b2aa",
    "lightskyblue": "87cefa",
    "lightslategray": "789",
    "lightslategrey": "789",
    "lightsteelblue": "b0c4de",
    "lightyellow": "ffffe0",
    "lime": "0f0",
    "limegreen": "32cd32",
    "linen": "faf0e6",
    "magenta": "f0f",
    "maroon": "800000",
    "mediumaquamarine": "66cdaa",
    "mediumblue": "0000cd",
    "mediumorchid": "ba55d3",
    "mediumpurple": "9370d8",
    "mediumseagreen": "3cb371",
    "mediumslateblue": "7b68ee",
    "mediumspringgreen": "00fa9a",
    "mediumturquoise": "48d1cc",
    "mediumvioletred": "c71585",
    "midnightblue": "191970",
    "mintcream": "f5fffa",
    "mistyrose": "ffe4e1",
    "moccasin": "ffe4b5",
    "navajowhite": "ffdead",
    "navy": "000080",
    "oldlace": "fdf5e6",
    "olive": "808000",
    "olivedrab": "6b8e23",
    "orange": "ffa500",
    "orangered": "ff4500",
    "orchid": "da70d6",
    "palegoldenrod": "eee8aa",
    "palegreen": "98fb98",
    "paleturquoise": "afeeee",
    "palevioletred": "d87093",
    "papayawhip": "ffefd5",
    "peachpuff": "ffdab9",
    "peru": "cd853f",
    "pink": "ffc0cb",
    "plum": "dda0dd",
    "powderblue": "b0e0e6",
    "purple": "800080",
    "red": "f00",
    "rebeccapurple": "663399",
    "rosybrown": "bc8f8f",
    "royalblue": "4169e1",
    "saddlebrown": "8b4513",
    "salmon": "fa8072",
    "sandybrown": "f4a460",
    "seagreen": "2e8b57",
    "seashell": "fff5ee",
    "sienna": "a0522d",
    "silver": "c0c0c0",
    "skyblue": "87ceeb",
    "slateblue": "6a5acd",
    "slategray": "708090",
    "slategrey": "708090",
    "snow": "fffafa",
    "springgreen": "00ff7f",
    "steelblue": "4682b4",
    "tan": "d2b48c",
    "teal": "008080",
    "thistle": "d8bfd8",
    "tomato": "ff6347",
    "turquoise": "40e0d0",
    "violet": "ee82ee",
    "wheat": "f5deb3",
    "white": "fff",
    "whitesmoke": "f5f5f5",
    "yellow": "ff0",
    "yellowgreen": "9acd32"
}

Save the file and you should see that nodemon has detected changes to the src folder and is running the prepare task again. The tests are still failing.

Next, inside src / lib folder, create a file named  utils . js and update it as shown below

const colorMap = require('./colors.json');
 
function hexToRGB(hex) {
  // https://stackoverflow.com/a/5624139/1015046
  // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
  const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
 
  hex = hex.replace(shorthandRegex, function(m, r, g, b) {
    return r + r + g + g + b + b;
  });
 
  const result = (/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i).exec(hex);
 
  return result ? {
    r: parseInt(result[1], 16),
    g: parseInt(result[2], 16),
    b: parseInt(result[3], 16)
  } : null;
}
 
export function processColor(colorName) {
  const color = {
    name: colorName
  };
 
  try {
    const hex = colorMap[colorName];
 
    if (!hex) {
      return false;
    }
 
    color.hex = `#${hex}`;
 
    const rgb = hexToRGB(color.hex);
    color.rgb = `rgb(${rgb.r}, ${rgb.g}, ${rgb.b})`;
 
  } catch (e) {
    /* istanbul ignore next */
    console.error('Something went wrong! Please try again.') // eslint-disable-line
  }
 
  return color;
}

On Line 1, we have required the colors hash. hexToRGB ( ) takes a HEX code and returns the RGB hash for the same.  processColor ( ) takes in the color name and returns the final result.

Save the file and still the tests do not pass.

Awesome! let’s continue

Update src / lib / index . js as shown below

const Utils = require('./utils.js');
 
export default function(colorNames) {
  if (!colorNames) {
    return 'Please provide a color name and try again.';
  }
 
  const results = [];
 
  if (typeof colorNames === 'string') {
    colorNames = colorNames.trim().split(' ');
  }
 
  for (let i = 0; i < colorNames.length; i++) {
    const colorHash = Utils.processColor(colorNames[i]);
    if (!colorHash) {
      return 'Sorry, this dosen\'t seem to be a valid Web color name';
    }
 
    results.push(colorHash);
  }
 
  // Dispatch an object for one color and array for multiple
  return results.length === 1 ? results[0] : results;
}

Here we are processing the options and responding accordingly.

Save the file and Boom! imIz6fJ.png!web

All the tests pass! And our NPM works!

Now, we will udpate src / cli . js as follows

#! /usr/bin/env node
 
import meow from 'meow';
import color2code from './lib/';
 
const cli = meow({
  help: [
    'Usage',
    '  $ color2code [input]',
    '',
    'Examples',
    '  $ color2code rebeccapurple',
    '',
    '   { ',
    '      "name": "rebeccapurple"',
    '      "hex": "#663399",',
    '      "rgb": "rgb(102, 51, 153)"',
    '   }'
  ]
});
 
const input = cli.input || [];
 
if (!input.length) {
  console.log(cli.help); // eslint-disable-line
} else {
  console.log(JSON.stringify(color2code(input), null, 4)); // eslint-disable-line
}

This concludes our development.

Simulate NPM install & Test

If you would like to simulate an NPM global install and test your app before publishing, you can do so by running the below command from inside the color2code folder

➜  color2code ✗ npm link .

And we should see something like

➜  color2code ✗ npm link .                                             
 
> [email protected] prepare /Users/aravulavaru/Documents/blog/code/color2code
> npm run build && npm run validate
 
 
> [email protected] build /Users/aravulavaru/Documents/blog/code/color2code
> babel -d ./ ./src --copy-files
 
src/cli.js -> cli.js
src/lib/index.js -> lib/index.js
src/lib/utils.js -> lib/utils.js
 
> [email protected] validate /Users/aravulavaru/Documents/blog/code/color2code
> npm run lint && npm test
 
 
> [email protected] lint /Users/aravulavaru/Documents/blog/code/color2code
> eslint src test
 
 
> [email protected] test /Users/aravulavaru/Documents/blog/code/color2code
> ava --require babel-core/register --verbose
 
 
(node:6406) DeprecationWarning: loudRejection/api is deprecated. Use the currently-unhandled module instead.
  ✔ color2code: no color name
  ✔ color2code: color name
  ✔ color2code: HEX value
  ✔ color2code: RGB value
  ✔ color2code: multiColors
  ✔ color2code: multiColors check red hex value
  ✔ color2code: multiColors check green hex value
  ✔ color2code: multiColors check red rgb value
  ✔ color2code: multiColors check green rgb
  ✔ color2code: invalid color name
  ✔ color2code: invalid color name multiple order 1
  ✔ color2code: invalid color name multiple order 2
 
  12 tests passed
 
up to date in 6.392s
/Users/aravulavaru/.npm-packages/bin/color2code -> /Users/aravulavaru/.npm-packages/lib/node_modules/color2code/cli.js
/Users/aravulavaru/.npm-packages/lib/node_modules/color2code -> /Users/aravulavaru/Documents/blog/code/color2code

And from anywhere on your machine you can run

➜  ~ ✗ color2code
 
  Get color code from color name
 
  Usage
    $ color2code [input]
 
  Examples
    $ color2code rebeccapurple
 
     { 
        "name": "rebeccapurple"
        "hex": "#663399",
        "rgb": "rgb(102, 51, 153)"
     }
➜  ~ ✗ color2code rebeccapurple         
{
    "name": "rebeccapurple",
    "hex": "#663399",
    "rgb": "rgb(102, 51, 153)"
}
➜  ~ ✗ color2code rebeccapurple tan peru
[
    {
        "name": "rebeccapurple",
        "hex": "#663399",
        "rgb": "rgb(102, 51, 153)"
    },
    {
        "name": "tan",
        "hex": "#d2b48c",
        "rgb": "rgb(210, 180, 140)"
    },
    {
        "name": "peru",
        "hex": "#cd853f",
        "rgb": "rgb(205, 133, 63)"
    }
]
➜  ~ ✗ color2code reed                  
"Sorry, this dosen't seem to be a valid Web color name"

Awesome right!

Code Coverage

We have written code and we have written test cases. Now, let’s take a look at the code coverage.

From inside color2code folder, run

➜  color2code ✗ npm run coverage

And we should see something like

➜  color2code ✗ npm run coverage                          
 
> [email protected] coverage /Users/aravulavaru/Documents/blog/code/color2code
> nyc --reporter=lcov --reporter=text --reporter=html npm test
 
(node:6634) Warning: process.on(SIGPROF) is reserved while debugging
 
> [email protected] test /Users/aravulavaru/Documents/blog/code/color2code
> ava --require babel-core/register --verbose
 
 
(node:6637) DeprecationWarning: loudRejection/api is deprecated. Use the currently-unhandled module instead.
  ✔ color2code: no color name
  ✔ color2code: color name
  ✔ color2code: HEX value
  ✔ color2code: RGB value
  ✔ color2code: multiColors
  ✔ color2code: multiColors check red hex value
  ✔ color2code: multiColors check green hex value
  ✔ color2code: multiColors check red rgb value
  ✔ color2code: multiColors check green rgb
  ✔ color2code: invalid color name
  ✔ color2code: invalid color name multiple order 1
  ✔ color2code: invalid color name multiple order 2
 
  12 tests passed
 
-----------|----------|----------|----------|----------|----------------|
File       |  % Stmts | % Branch |  % Funcs |  % Lines |Uncovered Lines |
-----------|----------|----------|----------|----------|----------------|
 lib/      |      100 |    83.33 |      100 |      100 |                |
  index.js |      100 |     87.5 |      100 |      100 |                |
  utils.js |      100 |       75 |      100 |      100 |                |
-----------|----------|----------|----------|----------|----------------|
All files  |      100 |    83.33 |      100 |      100 |                |
-----------|----------|----------|----------|----------|----------------|

You can also open coverage / index . html to view the report in the browser. It should look something like this

ya2222Q.png!web

So we are good to move our code to Github.

Push color2code to Github

You can push your fresh NPM to git to maintain it and let other people look-see/contribute to your code. For that we will follow the below steps

  1. Create a new Github repo:  https://github.com/new
  2. Run the following commands
➜  color2code ✗ git init
➜  color2code ✗ git add -A
➜  color2code ✗ git commit -am "Initial Commit"
➜  color2code ✗ git remote add origin [email protected]:arvindr21/color2code.git
➜  color2code ✗ git push origin master

PS: Update your repo URL as applicable

Voila! The code is deployed to Github. You can checkout my code here: arvindr21/color2code

Now that this is done, let’s setup Travis CI and Coveralls.

Setup Travis CI

Now that the repo is setup in Github, we will have a CI system in place. A Continuous Integration System keeps a tab on your repo for new changes and runs test cases on new changes and let’s you know if anything is broken.

Travis CI is a popular open source solution. You can read more about Travis CI here . We are going to use the same for managing our NPM.

If you open your Github repo, at the top of your readme, you should find a section as below

j2mYJnV.png!web

Click on “build | unknown” and you should be taken to Travis CI. In Travis CI, you should see a page like below

fYnUFji.png!web

Activate repository.

From next time onwards when ever there is a push to the repo, the CI will kick in and check if the build has passed.

Before we trigger a build, we will setup Coveralls.

Setup coveralls

Quoting from coveralls.io/continuous-integration

Coveralls takes the build data from whichever CI service your project uses, parses it, and provides constant updates and statistics on your projects’ code coverage to show you how coverage has changed with the new build, and what isn’t covered by tests. Coveralls even breaks down the test coverage on a file by file basis. You can see the relevant coverage, covered and missed lines, and the hits per line for each file, as well as quickly browse through individuals files that have changed in a new commit, and see exactly what changed in the build coverage.

Back to our repo and at the top of readme, click on “coverage | unknown” and you should be redirected to coveralls.io . Sign in and Click on the “+” sign in the menu on left hand side and search your repo here. Once you find it, enable coveralls for this repo.

FBRJ7fy.png!web And that is all, we are done.

Trigger Build

Now, let’s go back to Travis and trigger build from “More options” menu on the right hand side. And you should be shown a popup, fill it as applicable – trigger custom build yMb2iuJ.png!web

And once the build is completed, you should see something like this

2q2aMfa.png!web

Sweet right! Our NPM works from versions 4 to 10. Yay!!

This trigger will happen automagically when ever there is a new commit/Pull request.

The final step if build passes is to update coveralls. If we navigate to coveralls for our repo, we should see something like

eqqMvyi.png!web

We have a code coverage of 90%, which is good, considering we have only written few lines code.

We can also find out which files has what amount of coverage, as shown below

BFnQfqY.png!web

You can drill down further to analyse the issues.

With this we are done with our CI and Code coverage setup. If we go back to our Repo’s readme file, we should now see

fEv2euz.png!web

Now, we are going to publish the color2code to npmjs.com.

Publish color2code to NPM

To push color2code to NPM, we need to have an account with npmjs.com . Once you have signed up and activated your account, you can login to the same from your command prompt/terminal.

Run

➜  color2code ✗ npm login                             
Username: arvindr21
Password: 
Email: (this IS public) [email protected]
Logged in as arvindr21 on https://registry.npmjs.org/.

Once logged in, make sure you are at the root of color2code folder and run

➜  color2code ✗ npm publish

And boom your color2code NPM is published.

If you get an error, which mostly will happen because you have used the same name as mine – color2code . You need to use another name for your module in package . json file and then try publishing.

Your NPM is published. Navigate to npmjs.com/package/color2code to see the module we have just built.

With this our repo badges would look like

rEB3qiU.png!web

Hope you have learned how to build, publish and manage your own NPM!

Thanks for reading! Do comment.

@arvindr21


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK