How to Use esbuild in Rails for Fast JavaScript Bundling
To use
esbuild in Rails, add the jsbundling-rails gem and run rails javascript:install:esbuild to set up esbuild with default configs. Then use bin/dev to start the development server with esbuild bundling your JavaScript files.Syntax
Using esbuild in Rails involves running specific Rails commands and using configuration files to control bundling.
rails javascript:install:esbuild: Installs esbuild and sets up config files.bin/dev: Runs the development server with esbuild watching and bundling JS.package.json: Defines scripts and dependencies for esbuild.esbuild.config.js(optional): Customizes esbuild bundling options.
bash
rails javascript:install:esbuild # Then start dev server bin/dev
Example
This example shows how to install esbuild in a new Rails app and run it to bundle JavaScript.
bash
# Create new Rails app rails new myapp --skip-javascript cd myapp # Add jsbundling-rails gem to Gemfile # gem 'jsbundling-rails' bundle install # Install esbuild rails javascript:install:esbuild # Start development server with esbuild bundling bin/dev
Output
=> Booting Puma
=> Rails 7.x.x application starting in development
=> Run `bin/rails server --help` for more startup options
[esbuild] watching for changes...
Common Pitfalls
Common mistakes when using esbuild in Rails include:
- Not running
bin/devwhich starts both Rails and esbuild watchers. - Forgetting to add
jsbundling-railsgem before installing esbuild. - Not updating
package.jsonscripts if customizing build commands. - Trying to use legacy Webpacker config instead of esbuild setup.
bash
Wrong: # Running only rails server bin/rails server Right: # Run both Rails and esbuild watchers bin/dev
Quick Reference
| Command | Purpose |
|---|---|
| rails javascript:install:esbuild | Install esbuild and setup config |
| bin/dev | Start Rails server with esbuild watcher |
| yarn build | Run esbuild bundling once (production) |
| package.json scripts | Define custom esbuild commands |
Key Takeaways
Add the jsbundling-rails gem and run rails javascript:install:esbuild to set up esbuild in Rails.
Use bin/dev to run Rails server and esbuild watcher together during development.
Avoid using legacy Webpacker when using esbuild for JavaScript bundling.
Customize esbuild behavior via package.json scripts or esbuild.config.js if needed.
Remember to install node and yarn as prerequisites for esbuild in Rails.