@ledsun blog

無味の味は佳境に入らざればすなわち知れず

esbuild-rails

DHHが空のRailsアプリケーションにesbuildをインストールするGemを作りました。 中身を見てみます。

GitHub - rails/esbuild-rails: Bundle and transpile JavaScript in Rails with esbuild

You develop using this approach by running esbuild in watch mode in a terminal with npm run watch (and your Rails server in another, if you're not using something like puma-dev. Whenever esbuild detects changes to any of the JavaScript files in your project, it'll bundle app/javascript/application.js into app/assets/esbuilds/javascript.js. You can refer to the build output in your layout using the standard asset pipeline approach with <%= javascript_include_tag "application" %>.

npm run watch でesbuildに app/javascript/application.js を監視さます。 ビルドされたJavaScriptapp/assets/esbuilds/javascript.jsに配置されます。 Railsapp/assets/esbuilds/javascript.jsをassetsとして配信します。

次のように使うようです。

  1. Add esbuild-rails to your Gemfile with gem 'esbuild-rails'
  2. Run ./bin/bundle install
  3. Run ./bin/rails esbuild:install

Rakeタスクのesbuild:installを実行します。

https://github.com/rails/esbuild-rails/blob/v0.1.1/lib/tasks/esbuild/install.rake#L4

system "#{RbConfig.ruby} ./bin/rails app:template LOCATION=#{File.expand_path("../../install/install.rb",  __dir__)}"

rails app:templatehttps://github.com/rails/esbuild-rails/blob/v0.1.1/lib/install/install.rb を実行します。

Rails アプリケーションのテンプレート - Railsガイドによると

rakeタスクapp:templateを使って、既存のRailsアプリケーションにテンプレートを適用することもできます。テンプレートの場所はLOCATION環境変数で渡す必要があります。ここでも、ファイルパスまたはURLのどちらを使ってもかまいません。

中を読んでみましょう。

say "Compile into app/assets/esbuilds"
empty_directory "app/assets/esbuilds"
keep_file "app/assets/esbuilds"
append_to_file "app/assets/config/manifest.js", %(//= link_tree ../esbuilds .js\n)

if Rails.root.join(".gitignore").exist?
  append_to_file ".gitignore", %(\n/app/assets/esbuilds\n)
end

app/assets/esbuildsディレクトリを作って、.gitignoreに追加します。 途中は特別な事を指定なさそうなので、読み飛ばします。

say "Create default package.json and install esbuild"
copy_file "#{__dir__}/package.json", "package.json"
run "npm i esbuild"

https://github.com/rails/esbuild-rails/blob/v0.1.1/lib/install/package.json をコピーします。 esbuildをインストールします。

以上です。