Rails5の頃に作ったプロジェクトで、JS系のアセットの管理にはRails Assetsを使っている、Rails 5.1のプロジェクトが手元にありました。
先日(8/3)にそのRails Assetsが証明書の期限切れでbundle installできなくなるという問題が発生。 これを期に管理方法を変えないとねということで、Rails 5.1から使えるYarnを使うことにしました。
webpackerを使うのは遠すぎるのでやめました。
手順
node_modulesを読み込めるようにしておく
Rails 5.1へアップデートしたときに自動的に対応済になっていることが多い箇所ですが、asset pipelineのパスにnode_modulesを通しておきます。
1# config/initializers/assets.rb
2
3# ↓を追記
4
5# Add Yarn node_modules folder to the asset load path.
6Rails.application.config.assets.paths << Rails.root.join('node_modules')
package.jsonの用意
% yarn init
するとpackage.jsonが作られます。ただ、Railsが生成するファイルとは異なるので適当に削っておきます。おそらくdescriptionとか要らないはずなので。
こんな感じのファイルで良いはずです。
1{
2 "name": "my-project",
3 "private": true,
4 "dependencies": {}
5}
パッケージの追加
bootstrapが使うpopper.jsと、アプリケーションが使っていたjquery-confirmをyarnで入れてみます。
$ yarn add popper.js jquery-confirm
ついでにGemfileの不要な記述は消しておきます。
1-source 'https://rails-assets.org' do
2- gem 'rails-assets-popper.js'
3- gem 'rails-assets-jquery-confirm2'
4-end
requireを変更
1-#= require jquery
2-#= require popper
3-#= require jquery-confirm2
4
5+#= require jquery/dist/jquery.js
6+#= require popper.js/dist/umd/popper.js
7+#= require jquery-confirm/dist/jquery-confirm.min.js
popper.jsはdistに3種類あって正しいものを指定しないとsyntaxエラーとなります。トランスパイラを使わない場合はumd/以下のコードを参照する必要がありました。
1Popper.js is currently shipped with 3 targets in mind: UMD, ESM, and ESNext.
2No idea what am I talking about? You are looking for UMD probably.
3
4- UMD - Universal Module Definition: AMD, RequireJS, and globals;
5- ESM - ES Modules: For webpack/Rollup or browser supporting the spec;
6- ESNext: Available in /dist, can be used with webpack and babel-preset-env;
cssがあるパッケージの場合はそちらも変更する必要があります。
1-@import "jquery-confirm2"
2+@import "jquery-confirm/dist/jquery-confirm.min.css"
おわり
多分これら手順で動くはず。