LoginSignup
2

More than 5 years have passed since last update.

gulpで条件分岐する [gulp-if]

Last updated at Posted at 2018-12-16

このプラグインを使います

gulp-if
https://www.npmjs.com/package/gulp-if

このgulp環境を使って試します

gulpでphpをhtmlに変換する [gulp-php2html]
https://qiita.com/bonsai3/items/c33dfc902aed41899708

事前準備

package.json

package.json
{
    "name": "dev",
    "version": "1.0.0",
    "author": "",
    "main": "gulpfile.js",
    "license": "ISC",
    "devDependencies": {
        "gulp": "*",
        "gulp-php2html": "*",
        "gulp-if": "*"
    }
}

これを追加してあります

"gulp-if": "*"

gulpfile.js

gulpfile.js
// 設定
const config = {
    htmlOut: true
};

// 環境変数
const setting = {
    html: {
        src: "./root/*.php",
        dest: "./html"
    }
};

const gulp = require("gulp");

// phpからhtmlに変換するプラグインの読み込み
const php2html = require("gulp-php2html");

// 条件分岐するプラグインの読み込み
const gulpIf = require("gulp-if");

// phpからhtmlに変換するタスクを作成
gulp.task("html", () => {
    return (
        gulp
            // 変換対象のファイル
            .src(setting.html.src)
            // php→html変換
            .pipe(gulpIf(config.htmlOut, php2html()))
            // htmlを保存
            .pipe(gulp.dest(setting.html.dest))
    );
});

// ファイルの変更を監視してタスク実行
gulp.task("watch", () => {
    gulp.watch(setting.html.src, ["html"]);
});

// gulp起動時に実行するタスク
gulp.task("default", ["watch"]);

gulpfile.jsの変更点

「設定」を追加しました

// 設定
const config = {
    htmlOut: true
};

gulp-ifのプラグインを読み込んで

// 条件分岐するプラグインの読み込み
const gulpIf = require("gulp-if");

ここで分岐させてます

// php→html変換
.pipe(gulpIf(config.htmlOut, php2html()))

これで、config.htmlOutの設定値によって
gulpの動作を分岐させることができます。

普通にif文使えばいいのでは?

gulp-ifではなく、普通にJavascriptでif文使えばいいんじゃないの?
こういうことです↓

// phpからhtmlに変換するタスクを作成
gulp.task("html", () => {

//ここで条件分岐してしまう
if(config.htmlOut){
    return (
        gulp
            // 変換対象のファイル
            .src(setting.html.src)
            // php→html変換
            .pipe(php2html())
            // htmlを保存
            .pipe(gulp.dest(setting.html.dest))
    );
}

});

gulp-ifプラグインは、
「gulpの処理中」に「if」を突っ込めるところが便利なプラグインです。

なのでこういう細かい分岐をするために使います。

    return (
        gulp
            .src(setting.html.src)
            .pipe(gulpIf(何かのif分岐1,処理A)
            .pipe(gulpIf(何かのif分岐2,処理B)
            .pipe(gulpIf(何かのif分岐3,処理C)
            .pipe(gulpIf(何かのif分岐4,処理D)
            .pipe(処理)
            .pipe(gulp.dest(setting.html.dest))
    );

以上です。
ありがとうございました。

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
2