Rails 5.1 + webpacker + bootstrap の環境をCloud9で作るメモ

完全に自分用のメモです。

----

## リポジトリを作る

<img src="https://qiita-image-store.s3.amazonaws.com/0/74571/473657aa-724d-701e-da03-cfc494f69b78.png" width=240/>

---

![image.png](https://qiita-image-store.s3.amazonaws.com/0/74571/63cc8baf-7fed-78bf-e3bc-be2b82a6a700.png)

## rails newするまで

### 既存のworkspaceは一旦消す

```
yusukeiwaki:~ $ rm -rf ~/workspace/
yusukeiwaki:~ $ mkdir ~/workspace
yusukeiwaki:~ $ cd ~/workspace/
```

### railsをインストール

```
yusukeiwaki:~/workspace $ bundle init
```

すると `Gemfile` が作られるので、

```rb:Gemfile
# frozen_string_literal: true
source "https://rubygems.org"

git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }

gem "rails" #コメントアウトを外す
```

のように編集して

```
yusukeiwaki:~/workspace $ bundle install


Fetching gem metadata from https://rubygems.org/..........
Fetching version metadata from https://rubygems.org/..
Fetching dependency metadata from https://rubygems.org/.
Resolving dependencies...
Fetching rake 12.1.0
Installing rake 12.1.0
Using concurrent-ruby 1.0.5
(省略)
```

### rails new

オプションがいろいろある。

* `--webpack` オプションはあるけど、学習のために使わずにやってみる。
* 今回はsprocketsはskip
* rspec使うので、testもskip

```
yusukeiwaki:~/workspace $ bundle exec rails new . --skip-sprockets --skip-bundle --skip-test -f

       exist  
      create  README.md
      create  Rakefile
      create  config.ru
      create  .gitignore
       force  Gemfile
         run  git init from "."
Initialized empty Git repository in /home/ubuntu/workspace/.git/
      create  app
      create  app/assets/config/manifest.js
      create  app/assets/javascripts/application.js
      create  app/assets/javascripts/cable.js
      create  app/assets/stylesheets/application.css
      create  app/channels/application_cable/channel.rb
      create  app/channels/application_cable/connection.rb
      create  app/controllers/application_controller.rb
      create  app/helpers/application_helper.rb
      create  app/jobs/application_job.rb
      create  app/mailers/application_mailer.rb
      create  app/models/application_record.rb
      create  app/views/layouts/application.html.erb
      create  app/views/layouts/mailer.html.erb
      create  app/views/layouts/mailer.text.erb
      create  app/assets/images/.keep
      create  app/assets/javascripts/channels
      create  app/assets/javascripts/channels/.keep
      create  app/controllers/concerns/.keep
      create  app/models/concerns/.keep
      create  bin
      create  bin/bundle
      create  bin/rails
      create  bin/rake
      create  bin/setup
      create  bin/update
      create  bin/yarn
      create  config
      create  config/routes.rb
      create  config/application.rb
      create  config/environment.rb
      create  config/secrets.yml
      create  config/cable.yml
      create  config/puma.rb
      create  config/spring.rb
      create  config/environments
      create  config/environments/development.rb
      create  config/environments/production.rb
      create  config/environments/test.rb
      create  config/initializers
      create  config/initializers/application_controller_renderer.rb
      create  config/initializers/assets.rb
      create  config/initializers/backtrace_silencers.rb
      create  config/initializers/cookies_serializer.rb
      create  config/initializers/cors.rb
      create  config/initializers/filter_parameter_logging.rb
      create  config/initializers/inflections.rb
      create  config/initializers/mime_types.rb
      create  config/initializers/new_framework_defaults_5_1.rb
      create  config/initializers/wrap_parameters.rb
      create  config/locales
      create  config/locales/en.yml
      create  config/boot.rb
      create  config/database.yml
      create  db
      create  db/seeds.rb
      create  lib
      create  lib/tasks
      create  lib/tasks/.keep
      create  lib/assets
      create  lib/assets/.keep
      create  log
      create  log/.keep
      create  public
      create  public/404.html
      create  public/422.html
      create  public/500.html
      create  public/apple-touch-icon-precomposed.png
      create  public/apple-touch-icon.png
      create  public/favicon.ico
      create  public/robots.txt
      create  tmp
      create  tmp/.keep
      create  tmp/cache
      create  tmp/cache/assets
      create  vendor
      create  vendor/.keep
      create  package.json
      remove  config/initializers/assets.rb
      remove  config/initializers/cors.rb
      remove  config/initializers/new_framework_defaults_5_1.rb
```

### なんとなくバージョン管理登録

```
yusukeiwaki:~/workspace (master) $ git add -A
yusukeiwaki:~/workspace (master) $ git commit -a -m "initial commit"
```

## Webpackerを入れる

### webpacker Gemを追加

```diff:webpackerを追加
diff --git a/Gemfile b/Gemfile
index 5026c36..2148941 100644
--- a/Gemfile
+++ b/Gemfile
@@ -19,6 +19,8 @@ gem 'jbuilder', '~> 2.5'
 # Use ActiveModel has_secure_password
 # gem 'bcrypt', '~> 3.1.7'
 
+gem 'webpacker'
+
 # Use Capistrano for deployment
 # gem 'capistrano-rails', group: :development
 
```

で、あらためて

```
yusukeiwaki:~/workspace (master) $ bundle install

（ログ出力は省略）
```


### yarnのインストール

https://yarnpkg.com/en/docs/install#linux-tab に従う

```
curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -
echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list
sudo apt-get update && sudo apt-get install yarn
```

### webpackerの初期設定

```
yusukeiwaki:~/workspace (master) $ bundle exec rails webpacker:install

      create  config/webpacker.yml
Copying webpack core config and loaders
      create  config/webpack
      create  config/webpack/development.js
      create  config/webpack/environment.js
      create  config/webpack/production.js
      create  config/webpack/test.js
Copying .postcssrc.yml to app root directory
      create  .postcssrc.yml
Copying .babelrc to app root directory
      create  .babelrc
Creating javascript app source directory
      create  app/javascript
      create  app/javascript/packs/application.js
Copying binstubs
       exist  bin
      create  bin/webpack-dev-server
      create  bin/webpack
      append  .gitignore
Installing all JavaScript dependencies
         run  yarn add @rails/webpacker from "."
yarn add v1.1.0
info No lockfile found.
[1/4] Resolving packages...
[2/4] Fetching packages...

（以下省略...）
```

### javascript_pack_tag をlayout/application に入れる

```diff:javascript_pack_tagに置換
diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb
index 53f95d2..e0022d9 100644
--- a/app/views/layouts/application.html.erb
+++ b/app/views/layouts/application.html.erb
@@ -4,8 +4,7 @@
     <title>Workspace</title>
     <%= csrf_meta_tags %>
 
-    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
-    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
+    <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
   </head>
 
   <body>
```

今回はassetsパイプラインを使わないぞ！という割り切りで、↑のようにする。

ちなみに蛇足だが、ここで `app/javascript/packs/application.scss` みたいなファイル名でCSSを作ってしまうと、 `app/javascript/packs/application.js` がちゃんとビルドされなくて、ものすごくハマる！

### おためしで起動

```
yusukeiwaki:~/workspace (master) $ bin/webpack

Hash: 77d3b57fb7806bb9009c
Version: webpack 3.6.0
Time: 566ms
                              Asset      Size  Chunks             Chunk Names
application-8f8bdd9f4ff51391ec46.js   4.47 kB       0  [emitted]  application
                      manifest.json  68 bytes          [emitted]  
   [0] ./app/javascript/packs/application.js 515 bytes {0} [built]
```

でビルドして、

<img src="https://qiita-image-store.s3.amazonaws.com/0/74571/b4801840-0365-547f-73c3-dddb89ba6cab.png" width=240 />

ぽちっと。

![image.png](https://qiita-image-store.s3.amazonaws.com/0/74571/1b481844-f8f7-c454-7f41-154804dcd1c9.png)

うーん、これじゃあ動いてるかわからんｗｗ :sweat: 

### てきとうにページを作る

```
yusukeiwaki:~/workspace (master) $ bundle exec rails g scaffold Todo title:string description:text
      invoke  active_record
      create    db/migrate/20171002024501_create_todos.rb
      create    app/models/todo.rb
      invoke  resource_route
       route    resources :todos
      invoke  scaffold_controller
      create    app/controllers/todos_controller.rb
      invoke    erb
      create      app/views/todos
      create      app/views/todos/index.html.erb
      create      app/views/todos/edit.html.erb
      create      app/views/todos/show.html.erb
      create      app/views/todos/new.html.erb
      create      app/views/todos/_form.html.erb
      invoke    helper
      create      app/helpers/todos_helper.rb
      invoke    jbuilder
      create      app/views/todos/index.json.jbuilder
      create      app/views/todos/show.json.jbuilder
      create      app/views/todos/_todo.json.jbuilder
      invoke  assets
      invoke    js
      create      app/assets/javascripts/todos.js
      invoke    css
      create      app/assets/stylesheets/todos.css
      invoke  css
      create    app/assets/stylesheets/scaffold.css
yusukeiwaki:~/workspace (master) $ bundle exec rake db:migrate
== 20171002024501 CreateTodos: migrating ======================================
-- create_table(:todos)
   -> 0.0023s
== 20171002024501 CreateTodos: migrated (0.2001s) =============================
```

![image.png](https://qiita-image-store.s3.amazonaws.com/0/74571/f763221f-5975-2b2c-0d2e-d50f413fdfdf.png)


`Hello World from Webpacker` が出ていれば　おｋ！

### なんとなくバージョン管理

```
yusukeiwaki:~/workspace (master) $ git add -A
yusukeiwaki:~/workspace (master) $ git commit -a -m "webpacker"
```


## bootstrapの導入

ようやく・・・！

### package.jsonへの追加

```
yusukeiwaki:~/workspace (master) $ yarn add bootstrap@4.0.0-alpha.6 jquery popper.js                                                                                                    
yarn add v1.1.0
[1/4] Resolving packages...
[2/4] Fetching packages...
info fsevents@1.1.2: The platform "linux" is incompatible with this module.
info "fsevents@1.1.2" is an optional dependency and failed compatibility check. Excluding it from installation.
[3/4] Linking dependencies...
warning "postcss-cssnext@3.0.2" has unmet peer dependency "caniuse-lite@^1.0.30000697".
warning "webpack-dev-server@2.9.1" has unmet peer dependency "webpack@^2.2.0 || ^3.0.0".
[4/4] Building fresh packages...
success Saved lockfile.
success Saved 4 new dependencies.
├─ bootstrap@4.0.0-alpha.6
├─ jquery@3.2.1
├─ popper.js@1.12.5
└─ tether@1.4.0
Done in 6.00s.
```

### bootstrapを組み込む！

```diff:environment.jsの編集
diff --git a/config/webpack/environment.js b/config/webpack/environment.js
index d16d9af..86bf1a7 100644
--- a/config/webpack/environment.js
+++ b/config/webpack/environment.js
@@ -1,3 +1,10 @@
 const { environment } = require('@rails/webpacker')
 
+const webpack = require('webpack')
+environment.plugins.set('Provide', new webpack.ProvidePlugin({
+  $: 'jquery',
+  jQuery: 'jquery',
+  Popper: ['popper.js', 'default']
+}))
+
 module.exports = environment
```

```js:app/javascript/packs/application.js
import 'bootstrap/dist/js/bootstrap';

console.log('Hello World from Webpacker')
```

```css:app/javascript/packs/bootstrap.scss
@import '~bootstrap/dist/css/bootstrap';
```

```diff:stylesheet_pack_tagを追記
diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb
index e0022d9..b613fc9 100644
--- a/app/views/layouts/application.html.erb
+++ b/app/views/layouts/application.html.erb
@@ -4,6 +4,7 @@
     <title>Workspace</title>
     <%= csrf_meta_tags %>
 
+    <%= stylesheet_pack_tag 'bootstrap', media: 'all', 'data-turbolinks-track': 'reload' %>
     <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
   </head>

```


ここまでやると、

<img src="https://qiita-image-store.s3.amazonaws.com/0/74571/b5b47111-8efc-4e86-030f-84868da0277f.png" width=240 />

ちょっとオシャレ〜になる。いや、全然オシャレじゃないけど。

---

ためしに、

```
<%= link_to 'New Todo', new_todo_path, class: 'btn btn-primary' %>
```

みたいにしてみると

<img src="https://qiita-image-store.s3.amazonaws.com/0/74571/215dedff-d889-9de1-990c-143e64d21ca2.png" width=240 />

たしかにBootStrapが効いてることがわかります。