Railsアプリケーションに後から部分的にAngularを導入する

ruby -v
# ruby 2.6.3p62 (2019-04-16 revision 67580) [x86_64-darwin17]

rails -v
# Rails 5.2.3

bundler -v
# Bundler version 1.17.2

node -v
# v12.4.0

yarn -v
# 1.16.0

普通にアプリケーションを作成する

rails new . -T -O
rails g controller hello index
# config/routes.rb
Rails.application.routes.draw do
  root 'hello#index'
end
# 確認
bin/rails s

適当なjQueryを使う

echo "gem 'jquery-rails'" >> Gemfile
bundle
//= require jquery
<%= button_tag 'Hello', type: 'button', id: 'hello-jquery' %>
$ ->
  $('#hello-jquery').click ->
    alert('Hello jQuery')
# 確認
bin/rails s

WebpackerとAngularの導入

echo "gem 'webpacker'" >> Gemfile
bundle
rails webpacker:install
rails webpacker:install:angular
ls bin/
# bundle			setup			webpack
# rails			spring			webpack-dev-server
# rake			update			yarn
"dependencies": {
-   "core-js": "^3.1.4",
+   "core-js": "^2.5.7",
}
yarn install

jQueryとAngularの共存確認

<!-- app/views/layouts/application.html.erb -->
<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
<!-- app/views/hello/index.html.erb -->
<hello-angular>Loading...</hello-angular>
<%= javascript_pack_tag 'hello_angular' %>

起動

$ bin/webpack-dev-server
$ bin/rails s

angure_index

🎉🎉🎉🎉🎉🎉

コンパイル時に警告が出たり、最新のcore-jsが使えなかったり
使っている内にハマる危険がある