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:
In this post I share a quick (and simplified) summary to create a bundle for a React 18 / TypeScript project.
esbuild
in your projectmkdir 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"
}
}
Now create a simple React script:
react
and react-dom
as project dependenciessrc/App.tsx
fileApp
and Panel
components in the same fileApp
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
configurationCreate 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:
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
And you'll get the following output:
Your simple React 18 / TypeScript project should works :)