0
1

More than 3 years have passed since last update.

gulp を使用したSCSS(SASS)環境の構築

Posted at

普段はvsvcodeの拡張機能「Live Sass Compiler」を使用しているが、gulpを使用する機会があったので覚え書き

事前準備
Node.js https://nodejs.org/ja/
※インストール方法は@sefoo0104さんが紹介してくれているのでそちらを参照
Node.jsをインストールする

gulp(ガルプ)について詳しく知りたい方は公式サイトもしくはCodeGridを参照
・gulp 公式サイト
・CodeGrid 現場で使えるgulp入門

モジュール
Node.jsの設定が終わったら以下のモジュールをインストール
※今回はカレントディレクトリにインストール

一人で開発する場合(devDependencies)

> npm install --save-dev パッケージ名
> npm install -D パッケージ名

開発環境を共有する場合(dependencies)

> npm install --save-パッケージ名
> npm install -S パッケージ名

devDependenciesとdependenciesの違い
パッケージ(package.json)を公開した場合、開発者以外の人がnpm installを実行すると、dependenciesに記録されたパッケージがnode_modules内にインストールされ、devDependenciesに書かれているパッケージはインストールされません。

SASS、SCSSコンパイルに必要なモジュール

モジュール名 内容
gulp gulp本体
gulp-sass Sass/SCSSのコンパイル。sourcemapが使えない
gulp-ruby-sass gulp-sassと同じ処理だがこちらはsourcemapが使える
gulp-postcss CSSパーサとそれを取り扱うのに便利なAPIを提供しているツール

gulp-sassとgulp-ruby-sassはお好みの方を選択
※npmjsサイトで提供されているモジュールと設定方法が紹介されている
https://www.npmjs.com/

gulpを動かすにはgulpfile.jsが必要となるので、node_modulesと同じ階層に
gulpfile.jsを作成。
gulpfile.jsの書き方は@y_sekitobaさんが紹介しているのでそちらを参照
初めてのGulp入門 ~gulpfile入門~

上記で必要最低限の環境は構築できたが、このままでは面倒な手順を踏んでgulpをインストールした意味がいないので、下記のモジュールも合わせてインストールする。

モジュール名 内容
gulp-notify Mac,Linux,Windowに対してメッセージを通知する
gulp-plumber エラーが起きても処理を中断させない
autoprefixer コンパイル時にベンダープレフィックスを自動で記述してくれる

上記インストールが完了したらnpm list --depth=0でインストールされているパッケージ名を確認。

npm list --depth=0

+-- autoprefixer@9.8.6
+-- gulp@4.0.2
+-- gulp-notify@3.2.0
+-- gulp-plumber@1.2.1
+-- gulp-postcss@8.0.0
+-- gulp-sass@4.1.0

保存時に自動でCSSを作成
gulpfile.jsを下記に修正

gulpfile.js
/*
src 参照元を指定
dest 出力さきを指定
watch ファイル監視
series(直列処理)とparallel(並列処理)
*/
const { src, dest, watch, series, parallel } = require('gulp');

// プラグインを呼び出し
const sass = require('gulp-sass');
const plumber = require("gulp-plumber");
const notify = require("gulp-notify");
const postcss = require("gulp-postcss");
const autoprefixer = require("autoprefixer");

//参照元パス
const srcPath = {
  css: '../scss/*.scss',
}
//出力先パス
const destPath = {
  css: './css',
}

// 処理
const cssSass = () => {
 return src(srcPath.css) 
  .pipe(
    plumber(              //エラーが出ても処理を止めない
      {
        errorHandler: notify.onError('Error:<%= error.message %>')
        //エラー出力設定
      }
    )
  )
  .pipe(sass({
    outputStyle: "expanded"
  })
  )
  .pipe(postcss([autoprefixer({browsers: ['last 2 versions']})]))
  .pipe(dest(destPath.css))     //コンパイル先
}

/**
 * Sassファイルを監視し、変更があったらSassを変換します
 */
const watchSassFiles = () => watch(srcPath.css, cssSass);

// タスクをまとめて実行
exports.default = watchSassFiles;

対象のscss(sass)ファイルと出力先は任意に変更」

gulpの実行
カレントディレクトリに必要なパッケージが保存されているので、下記コマンドで実行

npx gulp

上記方法ではSCSS(SACC)のコンパイルを記述したが、LESSのコンパイルも用意されているので、LESSを使用している場合、必要なモジュールをインストールしてgulpfile.jsを修正。

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