Custom Tasks and Extensions

2018-02-24 15:52 更新

Sometimes, you'll want to hook your own Gulp tasks into Elixir. Perhaps you have a special bit of functionality that you'd like Elixir to mix and watch for you. No problem!

As an example, imagine that you have a general task that simply speaks a bit of text when called.

gulp.task("speak", function() {
    var message = "Tea...Earl Grey...Hot";

    gulp.src("").pipe(shell("say " + message));
});

Easy enough. From the command line, you may, of course, call gulp speak to trigger the task. To add it to Elixir, however, use the mix.task() method:

elixir(function(mix) {
    mix.task('speak');
});

That's it! Now, each time you run Gulp, your custom "speak" task will be executed alongside any other Elixir tasks that you've mixed in. To additionally register a watcher, so that your custom tasks will be re-triggered each time one or more files are modified, you may pass a regular expression as the second argument.

elixir(function(mix) {
    mix.task('speak', 'app/**/*.php');
});

By adding this second argument, we've instructed Elixir to re-trigger the "speak" task each time a PHP file in the "app/" directory is saved.

For even more flexibility, you can create full Elixir extensions. Using the previous "speak" example, you may write an extension, like so:

var gulp = require("gulp");
var shell = require("gulp-shell");
var elixir = require("laravel-elixir");

elixir.extend("speak", function(message) {

    gulp.task("speak", function() {
        gulp.src("").pipe(shell("say " + message));
    });

    return this.queueTask("speak");

 });

請(qǐng)注意我們 擴(kuò)增( extend ) Elixir 的 API 時(shí)所使用的第一個(gè)參數(shù),稍后我們需要在 Gulpfile 中使用它,以及建立 Gulp 任務(wù)所使用的回調(diào)函數(shù)。

如果你想要讓你的自定義任務(wù)能被監(jiān)控,只要在監(jiān)控器注冊(cè)就行了。

this.registerWatcher("speak", "app/**/*.php");

這行程序的意思是指,當(dāng)符合正則表達(dá)式 app/*/.php 的文件一經(jīng)修改,就會(huì)觸發(fā) message 任務(wù)。

很好!接著你可以將這行程序?qū)懺?Gulpfile 的頂端,或者將它放到自定義任務(wù)的文件里。如果你選擇后者,那么你必須將它加載至你的 Gulpfile,例如:

require("./custom-tasks")

大功告成!最后你只需要將他們結(jié)合。

elixir(function(mix) {
    mix.speak("Tea, Earl Grey, Hot");
});

加入之后,每當(dāng)你觸發(fā) Gulp,Picard 就會(huì)要求一些茶。

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)