Rails6でカスタムフォントを使用する方法


はじめに

Rails5では簡単にカスタムフォントを追加できたのですが、Rails6で追加するのに手こずりましたので、私が実際に試した方法を簡単にご紹介します。

環境

Ruby 3.0.1
Rails 6.1.3.1

① カスタムフォントの配置

まずカスタムフォントを GoogleFonts などから使用する素材をダウンロードし /app/assets/fonts 内にカスタムフォントファイルを配置します。

/app/assets/fontsフォルダがない場合は、/app/assets/内にfontsフォルダを作成してください。

② application.css の編集

application.cssにカスタムフォントの情報を記述していきます。

application.css
/*
 * 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
 */

@font-face {
    font-family: "NotoSansJP";
    font-style: normal;
    src: asset_url('NotoSansJP-Regular.otf') ;
}

.css のままだと Rails がカスタムフォントを認識してくれないので、.scssに拡張子を変更します。

  • Rails6からは、/app/assets/stylesheets 内の applicationファイルの拡張子が .cssで生成されるようになったようです。

③ assets:precompile の実行

コマンドで、rails assets:precompile を実行し変更を反映させます。

rails assets:precompile

無事反映ができていれば、コマンドの結果にコンパイルされたカスタムフォントのファイル名が表示されます。

最後に

カスタムフォントの反映ができず、インターネットで調べましたが、Rails6の情報が少なく解決しませんでした。
カスタムフォントがコンパイルされなかったので、ファイルを調べていると、applicationファイルの拡張子が .cssなのに気づき.scssに変更したところ上手く反映できました。
この事象に悩まされていた方のお役に立てれば幸いです。
以上、Rails6でカスタムフォントを使用する方法のご紹介でした。