Introduction to Esbuild
Esbuild is an extremely fast JavaScript bundler and minifier. It is designed to build large JavaScript applications with exceptional speed. In this guide, we will explore a multitude of Esbuild APIs with practical code snippets and create a simple app using these APIs.
Getting Started with Esbuild
To get started with Esbuild, install it via npm:
$ npm install esbuild
Basic Usage of Esbuild
const esbuild = require('esbuild'); esbuild.build({ entryPoints: ['src/app.js'], bundle: true, outfile: 'dist/bundle.js', }).catch(() => process.exit(1));
Transform API
Transform API allows you to convert a string of JavaScript or TypeScript code into standard JavaScript.
const transformed = esbuild.transformSync('const x: number = 1', { loader: 'ts' }); console.log(transformed.code);
Loader API
You can use different loaders for various file types to include them in your bundle.
const result = esbuild.buildSync({ entryPoints: ['src/app.tsx'], bundle: true, outfile: 'out.js', loader: { '.png': 'file' }, });
Plugin API
Esbuild supports custom plugins to enhance your build process.
const examplePlugin = { name: 'example', setup(build) { build.onResolve({ filter: /^example$/ }, args => ({ path: args.path, namespace: 'example-ns', })); }, }; esbuild.build({ entryPoints: ['input.js'], outfile: 'out.js', plugins: [examplePlugin], });
Serving Content
Esbuild can also be used to serve content during development.
esbuild.serve({ servedir: 'www', }, { entryPoints: ['app.js'], bundle: true, outfile: 'www/out.js', }).then(server => { console.log(`Server started on http://${server.host}:${server.port}`); });
Simple App Using Esbuild
Now, let’s create a simple React app utilizing the APIs we’ve discussed.
// Step 1: Install necessary dependencies $ npm install react react-dom // Step 2: Create an entry file src/index.jsx import React from 'react'; import ReactDOM from 'react-dom'; import './styles.css'; import Image from './image.png'; function App() { return (); } ReactDOM.render(Hello Esbuild!
![]()
, document.getElementById('root')); // Step 3: Styles in src/styles.css body { font-family: Arial, sans-serif; } // Step 4: Build the project using Esbuild esbuild.build({ entryPoints: ['src/index.jsx'], bundle: true, outfile: 'dist/bundle.js', loader: { '.png': 'file', '.css': 'css' }, }).catch(() => process.exit(1));
And that’s it! You’ve built a simple React application with Esbuild.
Note: Don’t forget to create an HTML file in the ‘dist’ directory to serve this application.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Esbuild React App</title> </head> <body> <div id="root"></div> <script src="bundle.js"></script> </body> </html>
Hash: 58515e9681237126916ae9760b47d9f8c6dec27108af55b9e8ec8c145d4ab7dd