2021.03.21

Node.js

gulp-postcssでpostcss-sortingを実行

gulp-postcssはgulp上でPostCSSが実行できます。postcss-sortingはPostCSSのプラグインで、CSSプロパティの記述順を並べ替えることができます。

gulp-postcssとpostcss-sortingを、それぞれバージョンを指定してインストールします。バージョンを指定しなければ最新バージョンがインストールされますが、最新バージョン通しの組み合わせではエラーが発生する場合があります。

//gulp-postcssバージョン8.0.0とpostcss-sortingバージョン5.0.1のインストール
npm install gulp-postcss@8.0.0 postcss-sorting@5.0.1

gulpfile.jsにpostcss-sortingの処理を追加します。gulp-postcss及びpostcss-sortingの実行はgulp-sass実行の後にする必要があります。postcss-sorting実行の箇所で、CSSプロパティの記述順を設定したpostcss-sorting.jsonを読み込みます。

//gulpfile.js
const gulp = require('gulp');
const sass = require('gulp-sass');
const sorting = require('postcss-sorting');  //postcss-sortingの読み込み
const postcss = require('gulp-postcss');  //gulp-postcssの読み込み

function styles() {
  return gulp
    .src('./src/scss/**/*.scss')
    .pipe(
      sass({
        outputStyle: 'expanded'
      })
    )
    .pipe(postcss([  //gulp-postcssの実行
      sorting(require('./postcss-sorting.json'))  //postcss-sortingの実行
    ]))
    .pipe(
      gulp
        .dest('../assets/css')
    );
}

gulp.task('default', styles);

postcss-sorting.jsonのproperties-orderにCSSプロパティの順序を指定します。unspecified-properties-positionはproperties-orderに記述されていないCSSプロパティの位置を指定します。bottomを指定すると順番は最後になります。

//postcss-sorting.json
{
  "properties-order": [
    "position",
    "z-index",
    "top",
    "right",
    "bottom",
    "left",
    …以下省略
  ],
  "unspecified-properties-position": "bottom"
}

これでpostcss-sortingが利用できるようになりました。gulpでsassをコンパイルすると、以下のようにCSSプロパティの順番が設定通りに並び替えられます。flex-wrapとalign-itemsはproperties-orderに記述されていないため、順番が最後になっているのがわかります。

//layout.css
@charset "UTF-8";

.p-access {
  display: flex;
  background: linear-gradient(to bottom, white, black);
  opacity: 1;
  animation: my_anime 3s;
  flex-wrap: wrap;
  align-items: center;
}

関連記事

2021.01.11

Node.js

パッケージのバージョン指定インストールとpackage-lock.json

パッケージインストール時にパッケージ名の後に@を付けると、パッケージのバージョンの指定ができます。以下はjqueryのバージョン3.4.1インストール時の指定で…

2021.01.16

Node.js

npm updateでパッケージのバージョンを更新

npm updateでパッケージのバージョンを更新します。更新を確認するためにまず、jqueryの古いバージョンである2.2.0をインストールします。 実行が完…

2021.03.10

Node.js

npm run-scriptでgulpを実行

ローカルにインストールしたnpmパッケージの実行は、npxコマンドを利用するのが簡単です。以下のgulpfile.jsでテストします。各タスクのfunction…

2021.03.20

Node.js

gulp-postcssでautoprefixerを実行

gulp-postcssはgulp上でPostCSSが実行できます。PostCSSはポストプロセッサーとして、コンパイル後のCSSに対して整形等の後処理ができま…

2021.01.11

Node.js

npm initによるpackage.jsonの作成とパッケージのインストール

プロジェクトを作成するディレクトリでnpm initを実行してpackage.jsonを作成します。対話形式で作成しますが何も入力せずEnterキーで進めていく…

上に戻る