LoginSignup
28
26

More than 5 years have passed since last update.

SassをGulpで自動コンパイルする

Last updated at Posted at 2017-03-08

Sassで記述したファイルをGulpを使って自動コンパイルする環境を構築するためのメモ書きです。

Gulpをインストールするまでの手順

npm(node.jsのパッケージ管理ツール)を使用して、Gulpをインストールします。

node.jsをインストール

以下のサイトより、node.jsをインストールします。
日本語公式サイトhttps://nodejs.org/ja/

package.jsonを生成

ここからは自動コンパイルの環境を構築したいプロジェクトのディレクトリに移動して作業します。
以下のコマンドを実行してpackage.jsonを生成します。

npm init

以下のような内容が表示されるので、必要な項目を入力していきます。

This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg> --save` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
name: (myproject) 
version: (1.0.0) 
description: My Project
entry point: (index.php)
test command: 
git repository: 
keywords: 
author: My Name
license: (ISC) 

完了すると、package.jsonが生成されます。

Gulpをインストール

以下のコマンドを実行してグローバルと開発用の両方にGulpをインストールします。

グローバルにGulpをインストール

npm install gulp -g

開発用にGulpをインストール

npm install gulp --save-dev

Sassを自動コンパイルするまでの手順

Gulpプラグインをインストール

使いたいプラグインをインストールします。
今回は以下のプラグインをインストールしました。

Sassコンパイラ

npm install gulp-sass --save-dev

ベンダープレフィックス自動化

npm install gulp-autoprefixer --save-dev

エラーハンドリング

npm install gulp-plumber --save-dev

gulpfile.jsの作成

gulpfile.jsを作成し、以下を記述します。

var path = require('path');
var fs = require('fs');
var pkg = JSON.parse(fs.readFileSync('./package.json'));
var assetsPath = path.resolve(pkg.path.assetsDir);

var gulp = require('gulp');

// sass compiler
var sass = require('gulp-sass');

// add vender prifix
var autoprefixer = require('gulp-autoprefixer');

// error handling
var plumber = require('gulp-plumber');

gulp.task('sass', function() {
    gulp.src(path.join(assetsPath, 'sass/main.scss'))
        .pipe(plumber())
        .pipe(sass())
        .pipe(autoprefixer())
        .pipe(gulp.dest(path.join(assetsPath, 'css/')));
});

gulp.task('default', function() {
    gulp.watch(path.join(assetsPath, 'sass/**/*.scss'),['sass']);
});

package.jsonにパスを追記

gulpfile.jsを他のプロジェクトでも使い回したいので、パスはpackage.jsonに記述するようにします。

"path": {
    "assetsDir": "./assets/"
},

SCSSファイル作成

sass/main.scssを作成します。
sassディレクトリ以下に複数のSCSSファイルを作成し、main.scssで@importすることも可能です。

実行

以下のコマンドを実行します。

gulp

すると、監視状態になり、SCSSファイルが変更・保存される度にcss/main.cssに自動でコンパイルされるようになります。

28
26
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
28
26