[How2Tips] How to create and publish an open source javascript library

David is one of the most experienced KNP devs.
Since 2013 he is Lead Dev, trainer and speaker here at KNP Labs. After a PhP period, he switched to JS, his Dada, his troll, his passion…

He also published some nice FOSS contributions… for example a little lib that will help you to boost your react app. In the following article he will explain how to publish an open source JS library.




Before starting : You must have `npm` or `yarn` installed on your environment with a working version of  `nodejs` of course.

The package.json

First thing first, if you want to publish an open source library, everything you have to do is to generate and edit the `package.json` file :

Let’s take an example with an imaginary `champion` lib :

Npm will ask some questions about your project, answer it now or later,
it does not matter.

Now you should have something like this inside your package.json :

Publishing your lib

In the folder of your library :

That’s it !

Testing your lib locally

You can `link` locally your lib :

Then in any other local projects :

Coding in ES6

You can install `webpack`, `browserify` or any bundle tools in development and code your projet in `ES6`.

Be sure to compile all your `src/` folder inside a `build/` or `dist/` or anything else.

Then you have the ability to hook the publishing process :

And now we can setup a build script :

There is plenty more scripts which you may find useful in the official documentation

Publishing Types

If you want your library to be popular and maintainable it’s always a good argument to add some `typing`. The most popular typing tool today is `typescript`.

You can create a `champion.d.ts` file anywhere you want and put your library types in there (or directly code with typescript).

Then you just have to specify where your types are in your `package.json` :

Writing `.d.ts` definition file is not that hard :)

Ignoring files to publish

If you have installed your lib inside some projet and you noticed that you have published all your tests with your lib (wich is rarely a good idea) then the `.npmignore` file in the root folder of your lib is probably missing  :

The previous lines will remove any references to `tests/` in the published package (it’s working the same way as a `.gitignore` file).

Curious to go further or work with us ? => hello@knplabs.com