Web Components and NPM

I’ve been using this article series to learn about web components for the first time this week, and I would highly recommend it. I’ve applied what I learned by creating a basic web component that counts down the days, hours, minutes and seconds to a specified date.

It’s on github at https://github.com/derekjohnson/count-down-web-component, and also on NPM at https://www.npmjs.com/package/count-down-web-component. Not only is it the first web component I’ve ever made, it’s the first thing I’ve ever published to NPM. I had to look in a few different places to get from start to finish, so jotted the process down here for next time, and anyone who finds it useful.

The good news is it’s not too bad. If you don’t already have Node.js installed you’ll need to do that first. Once that’s done follow these steps.

0. Put the project on github

Step 2 uses information about the github repository so make sure it’s on github with a README and a license.

1. Create an NPM account

Go to https://www.npmjs.com/signup and do the needful. You’ll need to click the link in a verification email before publishing.

2. Generate a package.json file

In your terminal navigate to your project folder and run npm init --yes. This creates a package.json file with best guesses based on the project files and some defaults.

I didn’t have to change much, added a few keywords that I think are there to make it more findable on npmjs.com, and changed the main value to the path of my web component JS. In my case it’s lib/countdown.js.

The main parameter isn’t required but it means that consumers of the component can load it with require('count-down-web-component') instead of require('count-down-web-component/lib/countdown.js') if that’s their thing.

There are other ways to create a package.json and documentation is at https://docs.npmjs.com/creating-a-package-json-file.

3. Login to NPM in terminal

Again in terminal run npm login. Enter your NPM username, password and email.

4. Publish

Finally run npm publish and your package will be live on NPM at https://www.npmjs.com/package/your-package-name


Hopefully my countdown component doesn’t stay at version 1.0.0 forever! For one thing it doesn’t stop when it reaches zero, it just ploughs right on ahead into negative time. I’d like to fix that and other things, so will need to update the package.

After committing changes to github use one of the following to update the NPM package:

This adheres to the semantic versioning specification, and more documentation about the npm version command is at https://docs.npmjs.com/cli/version.

Once that’s all done, run npm publish again and the package is updated.

I can’t see myself getting much deeper into NPM than that unless I have to, but as for web components I’m looking forward to learning a lot more about best practices and finding cool ways to progressively enhance web content.