LoginSignup
4
4

More than 3 years have passed since last update.

[Rails] application.scssのrequire_tree .に関して

Posted at

はじめに

"rails new"を実行して得られるファイルにapp/assets/stylesheets/application.scssってありますよね。

これまで学習したきた中で

*= require_tree .

の存在は知っていて、この記述があることで、stylesheetsディレクトリ内にある、scssファイルを読み込んでくれている、という認識でした。

それは間違いではないのですが、ある問題がおこって、あれ?ってなった

scssファイルが読み込まれて、、ない、、??

問題が起きたのは、以下のようなコードを書いた時です。

# application.scss

/*
 * This is a manifest file that'll be compiled into application.css, which will include all the files
 * listed below.
 *
 * Any CSS and SCSS file within this directory, lib/assets/stylesheets, or any plugin's
 * vendor/assets/stylesheets directory can be referenced here using a relative path.
 *
 * You're free to add application-wide styles to this file and they'll appear at the bottom of the
 * compiled file so the styles you add here take precedence over styles defined in any other CSS/SCSS
 * files in this directory. Styles in this file should be added after the last require_* statement.
 * It is generally better to create a new file per style scope.
 *
 *= require_tree .
 *= require_self
 */

 @import "reset";
 @import "config/colors";
 @import "font-awesome-sprockets";
 @import "font-awesome";

初心者の自分はこれで最初やってました。

"colors"っていうのは、よく使用する色を変数に変換してまとめているファイル(_colores.scss)です。
これで、アプリを立ち上げると、エラーになるはずです。

当時は、あれ?なんでだろ?って感じでわかっていませんでした。

上記のエラーを解消するには、以下のようにします。


 @import "reset";
 @import "config/colors";
 @import "font-awesome-sprockets";
 @import "font-awesome";

つまり、require_tree .を削除するということです。

require_treeには以下のような役割があります。

require_treeには引数として与えられたディレクトリ以下のCSSファイルをアルファベット順に全て読み込むという意味があります。require_treeの引数には.(ドット)が渡されています。引数.(ドット)はカレントディレクトリを表します。つまり、この記述によってapp/assets/stylesheetsというディレクトリにあるCSSファイルやSCSSファイルは全て読み込まれることになります。

要は、”require_tree .”によって、”@importで読み込んでいるファイル”より先にa~.scssのようなファイルを読み込み、結果として、変数を定義した_colors.scssが読み込まれた際にエラーが発生した、とういうことです。

だから、やり方としては2通りかな

  • require_treeを残す

 ※この場合は@importを記載する必要はないです。(font-awesomeとかは記載する)

  • require_treeを削除して、全てのscssファイルに対して@importの記述を行う

でも

おそらくreset.scssを使用すると思うので(たぶん)、その場合は、後者の選択になるかなと思います。

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