0
0

Rails7にpostCSSを導入しよう!

Last updated at Posted at 2022-10-26

前提

  • 事前にyarnのインストールが必要
    どうやら「Rails new」時に、postcssや、esbuildが「yarn」を使用してインストールされる模様
    ※別にnpmでいいや〜の私はこのせいで少し戸惑った💦

プロジェクトの作成

rails new . -j esbuild -c postcss
  • jオプションでJavaScriptのビルダー指定
  • cオプションで使用するCSSフレームワークにpostCSSを指定

色々インストールされる(適当)

package.jsonにscriptsが登録

yarn + 以下のコマンドで、ビルド処理が可能。

  • yarn build => JavaScriptのバンドル
  • yarn build:css => CSSファイルのバンドル処理

但し、Rails7にはbin/devコマンドが用意されているため、こちらを使用するのが一般的。
(CSS,JSの変更を検知して、自動でビルド処理してくれる優れもの)

gem "jsbundling-rails"gem "cssbundling-rails"を使用しているよ〜

"scripts": {
    "build": "esbuild app/javascript/*.* --bundle --sourcemap --outdir=app/assets/builds --public-path=assets",
    "build:css": "postcss ./app/assets/stylesheets/application.postcss.css -o ./app/assets/builds/application.css"
  } 

ビルド

CSS

$ yarn build:css
yarn run v1.22.19
$ postcss ./app/assets/stylesheets/application.postcss.css -o ./app/assets/builds/application.css
✨  Done in 1.09s.

JavaScript

yarn build
yarn run v1.22.19
$ esbuild app/javascript/*.* --bundle --sourcemap --outdir=app/assets/builds --public-path=assets

PostCSSの設定

プロジェクトのルートディレクトリに、postcss.configが作成されています。

module.exports = {
  plugins: [
    require('postcss-nesting'),
    require('autoprefixer'),
  ],
}

デフォルトでは、以下のプラグインを読み込んでいる

  • postcss-nesting
    => CSSのネスト記法をサポート

  • autoprefixer
    => ベンダープレフィックスの補完

このファイルに登録したプラグインがbuild:css時に実行されるよ〜

※ プラグインを追加登録したい場合は、従来通り、npm / yarnでインストールし、postcss.config.jsに登録

PostCSS便利なプラグインについて

  • autoprefixer
    デフォルトで実装されている
    ベンダープレフィックスを自動付与

  • postcss-nested
    デフォルトで導入されているpostcss-nesting では、ネストされたクラス属性へのスタイル適用が行えないため、Sassに慣れた私はこちらを使用している。

  • postcss-import
    @import記法をサポートしてくれる。ファイル分割が可能となる。

  • cssnano
    CSSをminify処理してくれる。本番環境では必須。

  • stylelint
    CSSのリンター。
    他のプラグインとは導入方法が異なるので、下で別途解説

Stylelint 導入方法

  • インストール
npm install stylelint --save-dev
  • プロジェクトのルートフォルダに、.stylelintrc.jsonを作成
    • 独自ルールを"rule"でオーバーライド
    • 基本的なコーディングルールをstylelint-config-standardから継承
      ※事前にnpm install stylelint-config-standard --save-dev が必要
{
    "extends": "stylelint-config-standard",
    "rules": {
        "indentation": 2,
    }
}
  • Stylelintの実行用スクリプトの登録
    package.jsonに以下を追記
"scripts": {
    "lint:css": "stylelint ./app/assets/stylesheets/*.{postcss,css,scss,sass}",
    "lint:fix": "stylelint --fix ./app/assets/stylesheets/*.{postcss,css,scss,sass}"
  },

以下のコマンドでstylelintの実行が可能

  • lint:css -> コードの検証
  • lint:fix -> コードの検証+構文の修正

まとめ

以上で作業完了です〜

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