How to Create a JavaScript Library. 7 Tips to Create a Library That Every Developer Loves Using

How to Create a JavaScript Library. 7 Tips to Create a Library That Every Developer Loves Using
Recommended Reading
AngularEngineeringJavaScriptReact

Why Would You Create a New JavaScript Library?

Have you ever found yourself copy-pasting the same bits of JavaScript code between different projects? Well, when this situation happens two or three times in a row, it’s usually a good indicator that you have a piece of code that is useful and reusable.

So, if you are already reusing your code across several different projects, why not go the extra mile and convert it into a library that allows you to optimize this code-sharing? Creating a library will allow you to build different versions, keep track of the bugs that you fix and know exactly which version is using each project.

This post is a compilation of tips and learnings from the Bugfender JS team. Take the following points into account when creating a new JavaScript library and other developers will be happy to use it.

What is the Best Way to Create a JavaScript Library?

A library is a blurry concept in JavaScript. There isn’t any specific format for it. There are, however, many specifications (although npm is the de facto standard).

While other platforms, like Android or iOS, clearly state what a library is, what format it must have and how it should be integrated into a project, JavaScript doesn’t provide any built-in mechanism. If you are a mobile developer and you’re looking for something like JAR or xcframeworks, you won’t find it.

Ok, So What Is a Javascript Library?

Whether you create your library using the npm structure or other modern standards, it can include any of the common development components, such as an instance, a class, a function, a primitive or an object (even an object containing all of the items listed before).

A JS library can be as complicated as a Singleton object, with its own life cycle and running its tasks in separate threads, or as simple as a file containing a set of handy tools.

What Is the Preferred Javascript Structure for a Library in 2020?

In the past, you would create a new file, paste your code and place this file in every project which required it. A common convention was grouping every used library into a project in the vendors folder. This practice was undermined by the fact that dependencies and versioning were difficult to manage. Also, when a library needed to use another library, there wasn’t a clear way to define this relationship. It was even common to find libraries that would copy-paste another full library inside to avoid dependency issues (unfortunately, duplicating a lot of code and hiding these dependencies from other developers).

For this reason, the most common way to create a library nowadays is by using npm. Libraries created for npm must follow an exact convention regarding their structure, so it is clear what the library does and what other dependencies are required.

We wrote a full tutorial on how to create and distribute a JavaScript library in an npm package, in which we combined the official workflow with many tips that we learnt developing Bugfender JS.

What If I Don’t Want to Use npm?

If you prefer to create your library in the simplest way possible, you can simply type your code into a JavaScript file and place this file in every project you want to use.

However, this adds the problem of versioning. Once you update your library, for example to fix a bug, you will need to manually update the file in every project. Use a local constant or even a comment to set a version number that can identify which version of the library you are using, so you have a quick way to identify which version is using each project.

Using a git repository in GitHub to keep track of the different release versions of your module is always a good idea.

If your library has dependencies with other libraries, remember to clearly document which other libraries, and which versions of them, are needed to use it.

It’s also worth taking into account that your module might need to be loaded in a particular order.

For example, when integrating Bugfender JS manually in a project, it is necessary to use the defer keyword.

Should I Use Pure Javascript or Typescript When Creating a New Library?

TypeScript is increasingly becoming the preferred choice when creating a new library. As TypeScript is a superset of JavaScript, all Typescript source code is directly compatible with all JavaScript projects. However, you get some perks when creating a Typescript library.

For example, before publishing your library with Typescript you will need to compile it. This process outputs the types of your library. The types can be understood as header files and those come in very handy when other developers adopt your code. A Typescript type is easy to read and understand because it is clearly stated which parameters should receive a function and what values will return.

Threading Management Inside a Javascript Library

In general, JavaScript engines are single-thread. However, if your library needs to perform some intensive work, you might be blocking the UI. In this case, Using Web Workers to run background tasks can be a good option.

Web workers come with a few constraints. For example, be careful with DOM manipulation, as it is not possible to directly manipulate the DOM or access some of the web APIs. But they are an excellent option for intensive network tasks involving sockets or data storage.

An example of web workers in Bugfender

We knew, from our experience with our mobile SDKs, that some users are going to push the SDK to the limits.

To give you an idea of the sheer diversity of developers using Bugfender, at one end of the scale we have game developers sending logs from Unreal Engine, an environment in which keeping a low footprint is mandatory to keep the frame rate as high as possible, and at the other end there are developers using Bugfender to debug the status of real-time sensors, sending hundreds of logs per second.

In the mobile platforms we are proud to say that these tasks are accomplished with an indistinguishable performance impact. That’s thanks to a good data structure (polished over several years) in tandem with good usage of background threads.

We wanted Bugfender JS to be capable of maintaining comparable performance across a wide variety of cases. So we are using Web Workers to do heavy-duty tasks like temporarily storing logs in the IndexedDB, until they can be sent to the Bugfender server.

Take Into Account the Order in Which Your Library Is Going to Be Loaded

When manually adding the Bugfender SDK to your web app, you need to use the defer key.

<script defer src="https://js.bugfender.com/bugfender.js"></script>

That’s because the order in which you load the scripts is not guaranteed. You should take this into account if you create a library by yourself and you want to access it from another script.

This is another reason to use npm. If you do it, everything will be preloaded in a big mountain of code in which everything is accessible and you won’t need to worry about it anymore.

What Are the Steps for Publishing My Javascript Library?

Whether this is a project for yourself, a project that you will share with your company team or an open-source project, first of all you need to document your code!

If you don’t add good documentation to your library, don’t be annoyed when your teammates start sending you private messages in Slack or emails asking how to use it.

Well actually, that’s a best-case scenario… usually they’ll just ignore your library!

Remember, nobody wants to spend their time reverse-engineering your code. Once your library is well-documented you can upload it to GitHub and share it (or even better, follow our tutorial and publish it to npm).

Where to Go From Here?

We at Bugfender are developers ourselves and we love to share our learnings with the community. You can subscribe to our spam-free quarterly newsletter in the box below, or you can continue reading one of these related posts:

If you can't see our comments box below, your browser's tracking protection may be blocking Facebook Comments.

as_websummit Created with Sketch. Slack Intel as_sk_telecom as_safedome

Already Trusted by Thousands

Bugfender is the best remote logger for mobile and web apps.

Get Started for Free, No Credit Card Required