DEV Community

Cover image for 🚀 Building your own Javascript Library with bare minimum
Gustavo Isensee
Gustavo Isensee

Posted on

🚀 Building your own Javascript Library with bare minimum

😄 Summarizing a bit, shall we?:

As you might know there are a lot of Javascript bundlers out there, such as webpack, sucrase, parcel, rollup 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.

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
and here some comparison I took from esbuild website
Image description

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:

mkdir my-library && cd my-library
Enter fullscreen mode Exit fullscreen mode

2. Initialise git and package.json

I'll be using yarn, if you wanna use yarn make sure you have it installed, or use npm equivalents commands:

git init
yarn init -y
touch .gitignore
Enter fullscreen mode Exit fullscreen mode

and don't forget to add these lines on your .gitignore file:

node_modules/
lib/
Enter fullscreen mode Exit fullscreen mode

3. Now let's install some packages

I'll be installing, only 3 packages: esbuild, rimraf and typescript.

yarn add esbuild rimraf typescript -D
Enter fullscreen mode Exit fullscreen mode

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:

"main": "lib/index.js",
"types": "lib/index.d.ts",
"scripts": {
  "ts-types": "tsc",
  "build": "rimraf lib && yarn ts-types && node ./esbuild.js"
}
Enter fullscreen mode Exit fullscreen mode

5. Create esbuild config

Create a file called esbuild.js on the root of the project:

touch esbuild.js
Enter fullscreen mode Exit fullscreen mode

and add these lines:

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));
Enter fullscreen mode Exit fullscreen mode

I hope they're self-explanatory, if not, you can check the esbuild configuration api here.

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:

touch tsconfig.json
Enter fullscreen mode Exit fullscreen mode

and add these lines:

{
  "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.*"]
}
Enter fullscreen mode Exit fullscreen mode

Again, I hope they're self-explanatory, if not you can check typescript config api here

7. You're ready to start coding

First, let's create a src folder and a index.ts file:

mkdir src && touch src/index.ts
Enter fullscreen mode Exit fullscreen mode

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:

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

export const times = (a: number, b: number) => a * b;
Enter fullscreen mode Exit fullscreen mode

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:

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

sum(2, 2); // 4
times(3, 3); // 9
Enter fullscreen mode Exit fullscreen mode

and in case you're using format: "csj", then:

const myLib = require('./lib/index');

myLib.sum(2, 2); // 4
myLib.times(3, 3); // 9
Enter fullscreen mode Exit fullscreen mode

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!

Top comments (0)