Getting Started with esbuild
Before diving into the advanced features and capabilities of esbuild, it’s important to start with the basics. This section will guide you through the initial setup and demonstrate how to use esbuild for building and bundling JavaScript files.
1. Installation and Setup
The first step in using esbuild is installing it. You can install esbuild globally or locally in your project. It’s generally recommended to install it locally so that it becomes part of your project’s dependencies.
Installation via npm:
npm install --save-dev esbuild
Installation via Yarn:
yarn add --dev esbuild
Once installed, you can use esbuild from the command line or through its JavaScript API.
2. Basic Usage
Let’s start with a simple example to see esbuild in action. Suppose you have a JavaScript file named app.js
:
// app.js
// A simple function that logs a message to the console
function greet() {
console.log('Hello, esbuild!');
}
// Call the greet function
greet();
To bundle this file using esbuild, you can run the following command:
npx esbuild app.js --bundle --outfile=bundle.js
Explanation of the command:
npx esbuild app.js
: This tells esbuild to process theapp.js
file.--bundle
: This flag indicates that esbuild should bundle the file and its dependencies.--outfile=bundle.js
: This specifies the name of the output file where the bundled code will be saved.
After running the command, you’ll see a new file named bundle.js
in your project directory. This file contains the bundled JavaScript code, ready to be included in your HTML.
3. Watching Files for Changes
One of the convenient features of esbuild is the ability to watch files for changes and automatically rebuild them. This is particularly useful during development when you’re frequently making changes to your code.
You can enable the watch mode by adding the --watch
flag:
npx esbuild app.js --bundle --outfile=bundle.js --watch
With the --watch
flag, esbuild will continuously monitor the app.js
file and automatically regenerate the bundle.js
file whenever changes are detected.
This setup ensures that you don’t have to manually rebuild your files each time you make a change, streamlining the development process.