5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rails6にmaterializeを導入する

Last updated at Posted at 2019-10-21

はじめに

遅ればせながらRails6触り始めました。
Rails6から標準のjsコンパイラがwebpackerに変更になったので、これまで通りにmaterializeを導入してもjs関連のいろいろが機能しません。今回は少し無理やりな方法ですが、「旧バージョンでmaterialieを導入済みで、rails6にアップグレードしてみたorしてみたい」人向けにとりあえず動かす方法の一案です。

なお、これから新規にアプリケーションを作成する場合はこちらの記事が参考になると思います。
How to install materialize-css on Rails 6.0.0.beta2 using Webpack

1. 準備

検証用に新規アプリケーションを立ち上げ、適当にscaffoldします。
からのGemfileにmaterializeを追加してbundle install

Gemfile
# materialize
gem 'materialize-sass'

app/assets/stylesheets/application.scssにてmaterializeをインポート

application.scss
@import 'materialize';

適当なviewファイルにinputを設置してみます。

index.html.erb
<%# 省略 %>
<div class="input-field">
  <input type="text" id="name" name='name'>
  <label for="name">name</label>
</div>

2. 確認

Image from Gyazo

上にピュッと移動するラベルが機能しませんね。アプリケーションをrails6にアップデートしたての方は同じような状況ではないでしょうか?

3. yarnでmaterialize-cssをインストール

該当アプリケーションのディレクトリに移動して
$ yarn add materialize-css
ちょっとRails6っぽいです。

app/javascript/packs/application.jsに以下を追記

application.js
import 'materialize-css/dist/js/materialize'

4. yarnでjqueryをインストール

Introducing jQuery in Rails 6 Using Webpackerこちらを参考にインストール願います。非常によくまとまってるのでペタペタしてるだけで1分程度で完了します。

5. 再度確認

Image from Gyazo

ぴょこぴょこ動いてますね。ここでは検証しませんが、その他のjsがらみのmaterialize(dropdownとかcollapsible)も私の環境では動いていることを確認しています。

6. 備考

今回は応急処置的な方法ということでgemとyarnで2種類のmaterializeをインストールしているため、ややお行儀の悪い感じがします。冒頭に貼った参考ではcssの読み込みもwebpackにやらせる方法が示されているので、気が向いたらお引越ししていこうかなと思います。

ちなみに、旧バージョンからのアップデートの場合はconfig/webpacker.ymlでwebpackのファイル探索範囲に旧assets下のjavascriptを追加するというのもありです。

webpacker.yml
  # Additional paths webpack should lookup modules
  # ['app/assets', 'engine/foo/app/assets']
  resolved_paths: ['app/assets']

以上、お困りの方の参考になれば幸いです。

7. 参考

How to install materialize-css on Rails 6.0.0.beta2 using Webpack
Introducing jQuery in Rails 6 Using Webpacker

5
5
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
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?