How to dev

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>

src/index.js:

console.log("Hello!");

the build command:

    "build": "esbuild --bundle src/index.js --outfile=dist/main.js"

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

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

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

the build output:

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

Links

Summary

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

Interested in reading more such articles from Marcin Wosinek?

Support the author by donating an amount of your choice.

 
Share this
Proudly part of