🚀 Building your own Javascript Library with bare minimum
Tags: library, esbuild
Published: 2022-06-29 15:15:56

---
title: 🚀 Building your own Javascript Library with bare minimum
published: true
description: 
tags: #library #esbuild
cover_image: https://miro.medium.com/max/1400/1*ZJ4KqXSsJzSInBv7FODKAQ.png
# Use a ratio of 100:42 for best results.
---

## :smile: Summarizing a bit, shall we?:

As you might know there are a lot of Javascript bundlers out there, such as [webpack](https://webpack.js.org/), [sucrase](https://sucrase.io/), [parcel](https://parceljs.org/), [rollup](https://rollupjs.org/guide/en/) and etc.
Bear in mind, not because they have thousands of stars on Github that means they're the best. sometimes new libs are as good as the popular ones but they're still building up their image/popularity in the community. what I bring today is a not sooooo, popular JS bundler called [esbuild](https://esbuild.github.io/).

For those who don't really know what a bundler does, here is a very simple explanation:
Your Javascript application might get bigger and bigger, so, you break it down in several files but you want to export everything in one or a few files, bundlers compile, transpile, compact, uglify, minify and other things for you. some have more features than others, and you need to analyse which one is better for your case.

But I will focus on **esbuild** in this article. so, let's check it out.

## 🏢 Why esbuild?

It supports all the new ecmascript specification and it is extremely faster than parcel, webpack and rollup.
you might be asking, but how? here are some points:

* It's written in Go and compiles to native code.
* Parallelism is used heavily.
* Everything in esbuild is written from scratch.
* Memory is used efficiently.

You can read more about each of these items [here](https://esbuild.github.io/faq/#why-is-esbuild-fast)
and here some comparison I took from esbuild [website](https://esbuild.github.io/)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l98jf2f80ndc3jl49o0m.png)

So, now that's proved that esbuild is very very veeeeery fast, let's get started with our first Javascript library.

## 🧑‍💻 Start coding

I love the KISS principle, so, let's keep it simple, open your terminal, navigate where you wanna have your project folder and follow these steps:

#### 1. Let's just create the folder and get in:
```shell
mkdir my-library && cd my-library
```

#### 2. Initialise git and package.json
I'll be using [yarn](https://yarnpkg.com/getting-started/install), if you wanna use yarn make sure you have it installed, or use npm equivalents commands:
```shell
git init
yarn init -y
touch .gitignore
```
and don't forget to add these lines on your `.gitignore` file:
```shell
node_modules/
lib/
```

#### 3. Now let's install some packages
I'll be installing, only 3 packages: `esbuild`, `rimraf` and `typescript`.
```shell
yarn add esbuild rimraf typescript -D
```
`rimraf` makes sure you can clean the folder specified in any OS, in case you have a CI on Windows, linux os macOS, all should be cleaned by rimraf.

`typescript` is very powerful and if you're not using it yet, please consider reading about the benefits of it.

#### 4. Editing `package.json`
Add in your package.json file the following lines:
```json
"main": "lib/index.js",
"types": "lib/index.d.ts",
"scripts": {
  "ts-types": "tsc",
  "build": "rimraf lib && yarn ts-types && node ./esbuild.js"
}
```

#### 5. Create esbuild config
Create a file called `esbuild.js` on the root of the project:
```shell
touch esbuild.js
```
and add these lines:

```javascript
const esbuild = require('esbuild');

esbuild
  .build({
    entryPoints: ['src/index.ts'],
    outdir: 'lib',
    bundle: true,
    sourcemap: true,
    minify: true,
    splitting: true,
    format: 'esm',
    target: ['esnext'],
    ignoreAnnotations: true
  })
  .catch(() => process.exit(1));
```
I hope they're self-explanatory, if not, you can check the esbuild configuration api [here](https://esbuild.github.io/api/).

**P.S.: If you're building a library for applications that don't support `import` and `export` from `esm` format, then consider using `format: "cjs"`. then remove `splitting` and edit format to `"cjs"`.**

#### 6. Let's create `tsconfig.json`
In case you decided not to have typescript, you can skip this step, otherwise follow these:
```shell
touch tsconfig.json
```
and add these lines:
```json
{
  "compilerOptions": {
    "emitDeclarationOnly": false,
    "declaration": true,
    "target": "es6",
    "lib": ["es6"],
    "strict": true,
    "noImplicitAny": false,
    "esModuleInterop": true,
    "moduleResolution": "node",
    "outDir": "lib",
    "skipLibCheck": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "**/*.test.*"]
}
```
Again, I hope they're self-explanatory, if not you can check typescript config api [here](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html)

#### 7. You're ready to start coding
First, let's create a `src` folder and a `index.ts` file:

 ```shell
mkdir src && touch src/index.ts
```
Let's do something very simple for testing purpose,
Create a sum and times functions that are exported, so we check them later from another context.
open your `index.ts` and add these lines:

```javascript
export const sum = (a: number, b: number) => a + b;

export const times = (a: number, b: number) => a * b;
```

#### 8. Now let's use it

if you used `format: "esm"` make sure you application supports `import` and `export` feature. then you can simply do:

```javascript
import { sum, times } from './lib/index'; // path might differ where you are.

sum(2, 2); // 4
times(3, 3); // 9
```

and in case you're using `format: "csj"`, then:
```javascript
const myLib = require('./lib/index');

myLib.sum(2, 2); // 4
myLib.times(3, 3); // 9
```

## In conclusion

I know it's quite a long post, but still, very simple and pragmatic. In practice we created a super tiny javascript library with `esbuild` and `typescript` with only 3 libs, and this can be improved even more, maybe `nodemon` to rebuild every time you change something in your src folder, testing with `jest`, or publishing it to npm, and other nice things. but so far, we got something useful, powerful and simple, easy to maintain and way faster than some of the bundlers mentioned, so, I hope you liked it, more posts coming up soon, see you next soon!