DEV Community

Marcin Wosinek
Marcin Wosinek

Posted on • Updated on • Originally published at how-to.dev

How to bootstrap JavaScript project with esbuild

This article will present a simple code generator for kicking off a browser project that uses esbuild as a bundler.

Code generator

For generating code, I'm using degit. It allows you to start a new project directly from a GitHub repository without dragging anything besides flat files from the original repository. So you can focus on your project instead of cleaning up the starter references.

Code

The application is greatly simplified, and it's very similar to the minimal code example I use in my blog.

index.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>webpack</title>
    <meta name="viewport" content="width=device-width,initial-scale=1" />
    <script defer="defer" src="dist/main.js"></script>
  </head>
  <body></body>
</html>
Enter fullscreen mode Exit fullscreen mode

src/index.js:

console.log("Hello!");
Enter fullscreen mode Exit fullscreen mode

the build command:

    "build": "esbuild --bundle src/index.js --outfile=dist/main.js"
Enter fullscreen mode Exit fullscreen mode

Usage

To start a new esbuild project, you can run:

npx degit how-to-js/esbuild-starter new-project
npx: installed 1 in 1.968s
> cloned how-to-js/esbuild-starter#HEAD to new-project
Enter fullscreen mode Exit fullscreen mode

After getting basic files, we can install dependencies:

npm install

> esbuild@0.12.24 postinstall /home/marcin/workspace/github/tmp/new-project/node_modules/esbuild
> node install.js

npm notice created a lockfile as package-lock.json. You should commit this file.
added 1 package and audited 1 package in 0.664s
found 0 vulnerabilities
Enter fullscreen mode Exit fullscreen mode

and build our code:

$ npm run build

> esbuild-starter@1.0.0 build /home/marcin/workspace/github/tmp/new-project
> esbuild --bundle src/index.js --outfile=dist/main.js


  dist/main.js  58b 

⚡ Done in 1ms
Enter fullscreen mode Exit fullscreen mode

the build output:

(() => {
  // src/index.js
  console.log("Hello!");
})();
Enter fullscreen mode Exit fullscreen mode

Links

Summary

I hope this little code generator will help you start with esbuild.

Discussion (0)