LoginSignup
0

More than 5 years have passed since last update.

stylelint で設定できるAMP 用のルール

Last updated at Posted at 2018-10-12

前提

  • AMP ページのスタイルも stylelint の対象にしたい、という方向けです。
  • なお、プルリク作成時にCircleCI経由で実行させることを想定しています。
  • AMP ページのスタイルは基本的に <style> 内に書かれているので、別途プロセッサ stylelint-processor-arbitrary-tags のインストールが必要です。

環境

  • stylelint @9.5.0
  • npm 6.0.0
  • Ruby On Rails 5.2.0
  • CircleCI

TL;DR

AMPに必要なルールだけを抜粋すると以下の通りです。

.stylelintrc.amp.yml
processors: ["@mapbox/stylelint-processor-arbitrary-tags"]
rules:
  ...
  declaration-no-important: true
  declaration-property-value-whitelist:
    transition: [/^(opacity|transform)\s\d*(\.\d+)*s\s(ease|ease-in|ease-out|ease-in-out|linear|step-start|step-end|step|cubic-bezier|frames)+/]
  selector-class-pattern: "^(?!.*-amp-).+$"
  ...

なお、AMPでは @keyframes 内に書いていいプロパティが制限されているんですが、stylelintのルールでは現状できないようなので、本ファイルでは考慮していません。
https://www.ampproject.org/docs/design/responsive/style_pages#restricted-styles

詳細

AMP ページでは、書いてはいけない CSS 、制限のある CSS が定められています。
スクリーンショット 2018-10-12 12.02.08.png

禁止されている CSS

  • !important を使用してはいけない
  • <link rel="stylesheet"> を使用してはいけない
  • -amp- で始まるクラス、i-amp タグをセレクターとして使用してはいけない

制限のある CSS

  • transition プロパティには、opacity|transform|-vendorPrefix-transform のどれかしか使ってはいけない(正確に言うとGPUを使用する値しか使ってはいけない。今後CSSの仕様が変わって増えることもあるかも…?)。
  • @keyframes 内では、 opacity|transform|-vendorPrefix-transform のどれかしか使ってはいけない(正確に言うとGPUを使用する値しか使ってはいけない。今後CSSの仕様が変わって増えることもあるかも…?)。

stylelint で指定できるAMPのルール

上記のルールのうち、現状で stylelint で指定できるルールは以下のみです。
- !important
- -amp- クラス、 i-amp タグ
- transition

<link> タグはそもそもスタイルを検知できなさそうなのでさておき、 @keyframes!important 使っちゃだめ!というルールはあるんですが、それ以外はなさそうな感じです。

CircleCI で自動で stylelint を実行

このあたりはプロジェクトによるのでおまけなんですが、自分の関わっているプロジェクトでは、いちいち手動で stylelint を実行するのはめんどくさいので、プルリクを出した段階で回る CircleCI 上で実行させています。

以下 のように、 lint というジョブを用意して、その中でスクリプトを実行させています。

.circle/config.yml
...
  lint:
    steps:
      - attach_workspace:
          at: ~/project
      - run:
         name: Run stylelint
         command: bash ./.circleci/stylelint_exec.sh
...

スクリプトの中身を抜粋するとこんな感じです。 master と差分のあるファイル(html|erb|scss|css)を抽出して、 diff_files に保存。それを for 文で回して、 .amp 拡張子のついたファイルだけに AMP 用の設定ファイルを適用して stylelint を実行しています。

stylelint_exec.sh
for diff_file in $diff_files; do
  if [[ $diff_file =~ \.amp ]]; then
    ./node_modules/.bin/stylelint -f verbose $diff_file --config .stylelintrc.amp.yml
  else
    ./node_modules/.bin/stylelint -f verbose $diff_file --config .stylelintrc.yml
  fi
done

参考文献

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