LoginSignup
3
4

More than 5 years have passed since last update.

SassをGulp4で監視して自動コンパイルする

Last updated at Posted at 2019-01-16

Gulpを弄るに先立っていろいろ検索して、例文をそのままコピペしても、正常に動かない場合が多いです。その理由として、Gulp4ではそれ以前と異なる構文があるからです。なので、実際僕が試行錯誤して生み出したGulp4で動く、『Sassファイルの変更を監視して、変更があれば .css と .min.css を生成するgulpfile.js』をここに置いておこうと思います。

// 実行環境
gulp -v
CLI version 2.0.1
Local version 4.0.0

Sassファイルの変更を監視して、変更があれば .css と .min.css を生成する gulpfile.js

gulpfile.js
var gulp = require('gulp');
var sass = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
var notify = require('gulp-notify');
var rename = require('gulp-rename');
var cleanCSS = require('gulp-clean-css');

// Sassをコンパイルするタスクの設定
gulp.task("css", function () {
    return gulp.src('node_modules/bootstrap/scss/*.scss')// コンパイル対象のSassファイル
            .pipe(sass()) // コンパイル実行
            .pipe(autoprefixer()) // ベンダープレフィックスの付与
            .pipe(gulp.dest('node_modules/bootstrap/dist/css')); // 出力
});

// .min.cssを生成するタスクの設定
gulp.task("mincss", function () {
    return gulp.src('node_modules/bootstrap/dist/css/bootstrap.css')//上のタスクで出力したcssファイル
            .pipe(cleanCSS()) // cssを圧縮
            .pipe(rename({extname:'.min.css'})) // 名前を.min.cssにする
            .pipe(gulp.dest('node_modules/bootstrap/dist/css')) // 出力
            .pipe(notify({
                title: 'bootstrap.cssとbootstrap.min.cssをコンパイルしました。',
                message: new Date(),
                sound: 'Pop',
                icon: 'icon.png' // 適当なアイコンを追加してみてください
            }));
});

gulp.task("default", function () {
    // scssフォルダを監視し、変更があったらコンパイルする
    gulp.watch('node_modules/bootstrap/scss/*.scss',gulp.series('css', 'mincss'));
});

それぞれのプラグインは事前にインストールしておいてください。

$ npm install --save-dev gulp-sass
$ npm install --save-dev gulp-autoprefixer
$ npm install --save-dev gulp-notify
$ npm install --save-dev gulp-rename
$ npm install --save-dev gulp-clean-css

Gulpのインストール等は以下の記事をご参照ください。
Bootstrap 4のCSSコンパイルをGulpで管理する方法

この記事がお役に立てれば幸いです。ご指摘等はお気軽にお願いします。

3
4
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
3
4