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:
- First, install
react
andreact-dom
as project dependencies - Create the
src/App.tsx
file - Add
App
andPanel
components in the same file - Mount
App
component in adiv
element withroot
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:
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
And you'll get the following output:
Your simple React 18 / TypeScript project should works :)
SlideShare Presentation
Top comments (0)