LoginSignup
3
1

More than 1 year has passed since last update.

【Rails】Javascriptバンドラーの第5の選択肢vite_rails

Last updated at Posted at 2022-08-16

初めに

Rails7からアセットパイプラインはimportmap esbuild webpack rollupの 4 つの選択肢があります。
ですが、新たにvite_railsという選択肢をここで紹介させていただきます。

なぜ vite_rails なのか

  • 開発サーバーは非常に高速に起動し、変更が即座に更新される。(ホットリロード)
  • 基本的にデフォルトの設定で動作し、構成が簡単である
  • デプロイ時はassets:precompileでバンドルができる。
  • css や sass などもバンドルできる。

導入方法

webpackerからの移行する方法になります。

Gemfilevite_railsを追加します。

Gemfile
gem 'vite_rails'
ターミナル
$ bundle install

$ bundle exec vite install
設定ファイルを作成する

デフォルトではapp/frontendがエントリーポイントになっていますので、app/javascriptに変更します。

config/vite.json

{
  "all": {
    "sourceCodeDir": "app/javascript",
  }
  // 省略
}

application.html.erbにある読み込みのタグヘルパーを変更する。

app/views/layouts/application.html.erb

- <%= javascript_packs_with_chunks_tag 'application' %>
+ <%= vite_javascript_tag 'application' %>

そして、require.contextimport.meta.globEagerに書き換える。

- const context = require.context("./controllers", true, /\.js$/)
+ const controllers = import.meta.globEager('./**/*_controller.js')

参考

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1