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;
}





