emote with ES logo

ESBuild and React

Hello world example

Create and build a simple React/TypeScript project with "esbuild"

2022-09-01
4 min read
Difficulty
esbuild
react
typescript
emote with ES logo

TOPICS

Introduction

esbuild is a fast javascript bundler that is 10-100x faster than webpack, rollup or parcel and it is used by tool like ViteJS.

It supports features such as:

  • ES6 and CommonJS modules
  • Tree shaking of ES6 modules
  • An API for JavaScript and Go
  • TypeScript and JSX syntax
  • Source maps
  • Minification
  • Plugins
  • and more....

In this post I share a quick (and simplified) summary to create a bundle for a React 18 / TypeScript project.

Install esbuild in your project

mkdir esbuild-demo
cd esbuild-demo
npm init -y
npm install esbuild

This generates the following package.json:

{
  "name": "esbuild-demo-story",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "esbuild": "^0.14.48"
  }
}

Create a React 18 / TypeScript project

Now create a simple React script:

  1. First, install react and react-dom as project dependencies
  2. Create the src/App.tsx file
  3. Add App and Panel components in the same file
  4. Mount App component in a div element with root id
// src/App.tsx
import * as React from 'react'
import ReactDOM from 'react-dom/client';

// App Component
const App = () => (<div>
  <h1>Hello, ESBUILD!</h1>
  <Panel />
  <Panel />
</div>)

// Panel Component
const Panel = () => <h2>I'm a Panel</h2>

// Mount component 
const root = ReactDOM.createRoot(
  document.getElementById('root')
);
root.render(<App />);

esbuild configuration

Create an esbuild configuration file to compile the project. It will generate a (minified) bundle in the dist folder that also includes React and ReactDom libraries (you can exclude them by using the external property:

// esbuild.config.js
const res = require('esbuild').buildSync({
  entryPoints: ['src/app.tsx'],
  bundle: true,
  minify: true,
  format: 'cjs',
  sourcemap: true,
  outfile: 'dist/output.js',
  // external: ['react', 'react-dom'], 
})

Run the configuration file by using Node:

node esbuild.config.js

Project Folder:

alt text for accessibility

Index.html

Create an index.html in the project root folder and import your bundle:

<html>
  <body>
  <script type="module" src="./dist/output.js"></script>
  <h1>React</h1>

  <div id="root"></div>
  </body>
</html>

Run a webserver:

npx lite-server

liteserver preview

And you'll get the following output:

Final preview

Your simple React 18 / TypeScript project should works :)

Video Tutorial (45 min - Italian only )

Slides

Keep updated about latest content
videos, articles, tips and news