esbuild for Rails

Episode #313 by David Kimura

Summary

Use esbuild to bundle your JavaScript, then deliver it via the asset pipeline in Rails. This gem provides an installer to get you going with esbuild in a new Rails application.
7.0 javascript rails assets 6:12

Resources

Update: jsbundling-rails


Since the time of recording, the esbuild-rails library has been archived in favor for jsbundling-rails which combines esbuild, rollupjs and webpacker into a single library. You should be able to use this instead with the new syntax found at https://github.com/rails/jsbundling-rails

bin/rails javascript:install:esbuild
bin/rails javascript:install:rollup
bin/rails javascript:install:webpack

Update: cssbundling-rails


In addition to the jsbundling, we also now have cssbundling-rails which will bring in the necessary components to handle our assets. With this change, forman has been introduced and will allow you to start your rails application, the yarn watch for css and the yarn watch for javascript with 

bin/dev

What this means as far as this episode content goes, is that I would no longer include the node_modules in the assets, but rather just import bootstrap into my stylesheets.

# app/assets/stylesheets/application.scss
@import 'bootstrap/scss/bootstrap';

With the addition of this gem, we are given a few additional options in the generators.

rails css:install:[tailwind|bootstrap|postcss|sass]
Download Source Code

Summary

# Terminal
bundle add esbuild-rails
bin/rails esbuild:install
yarn build --watch
yarn add bootstrap

# app/javascript/application.js
// Entrypoint for the esbuild command defined in package.json scripts
import bootstrap from "bootstrap/dist/js/bootstrap.bundle"

new bootstrap.Popover(document.querySelector('[data-bs-toggle="popover"]'), {
  trigger: 'hover'
})

# app/assets/stylesheets/application.css
/*
 *= require "bootstrap"
 *= require_tree .
 *= require_self
 */

# config/initializers/assets.rb
Rails.application.config.assets.paths << 'node_modules'