GithubHelp home page GithubHelp logo

gulp-require-tasks's Introduction

gulp-require-tasks

npm version

This convenient extension for Gulp 3 allows you to load tasks from multiple individual files in a directory hierarchy.

Deprecation Notice

This extension is deprecated and archived! Use Gulp 4 with Gulp Hub instead.

PRs are not being accepted. Consider creating a fork if you really want it.

Features

  • Loads individual task files recursively from the specified directory
  • The name of the task is inferred from the directory structure, e.g. styles:preprocess:clean
  • Easily integrates into the gulpfile.js without breaking your existing tasks
  • Gulp instance and task callback are automatically passed to your task function
  • Very flexible: almost all aspects of the module is configurable
  • Each task is stored in it's own local node module to completely separate concerns

Installation

npm i -D gulp gulp-require-tasks

Usage

Create a directory alongside your gulpfile.js to store your individual task modules, e.g. ./gulp-tasks. Place your tasks into this directory. One task per JavaScript file. Use sub-directories to structure your tasks.

Load tasks from your gulpfile.js:

// gulpfile.js:

// Require the module.
const gulpRequireTasks = require('gulp-require-tasks');

// Invoke the module with options.
gulpRequireTasks({

  // Specify path to your tasks directory.
  path: process.cwd() + '/gulp-tasks' // This is default!

  // Additionally pass any options to it from the table below.
  // ...

});

// Or, use minimal invocation possible with all options set to defaults.
gulpRequireTasks();

Minimal Gulp file possible

// gulpfile.js:
require('gulp-require-tasks')();

Or with options:

// gulpfile.js:
require('gulp-require-tasks')({
  separator: '.'
});

Options

Property Default Value Description
path './gulp-tasks' Path to directory from which to load your tasks modules
separator : Task name separator, your tasks would be named, e.g. foo:bar:baz for ./tasks/foo/bar/baz.js
passGulp true Whether to pass Gulp instance as a first argument to your task function
passCallback true Whether to pass task callback function as a last argument to your task function
gulp require('gulp') You could pass your existing Gulp instance if you have one, or it will be required automatically

Task module format

Consider you have the following task module: gulp-tasks/styles/build.js.

Module as a function

You could define module as a task function. Gulp instance and callback function would be passed to it, if not configured otherwise.

You could configure the library to pass additional arguments as well.

// gulp-tasks/styles/build.js:

const compass = require('compass');

module.exports = function (gulp, callback) {
  return gulp.src('...')
    .pipe(compass())
    .pipe(gulp.dest('...'))
  ;
};

Module as an object

Also, you could define your task module as an object. This will allow you to provide additional configuration.

// gulp-tasks/styles/build.js:

const compass = require('compass');

module.exports = {
  deps: ['styles:clean', 'icons:build'],
  fn: function (gulp, callback) {
    return gulp.src('...')
      .pipe(compass())
      .pipe(gulp.dest('...'))
    ;
  }
};

You will have to define your task function as fn parameter. You could use deps parameter to define your task dependencies.

Also, you could use nativeTask instead of fn property to make your task function executed by Gulp directly. That way, additional arguments will not be passed to it. This feature is useful when using, e.g. gulp-sequence plugin or for synchronous tasks.

Task function return value

To make sure, that task is finished correctly you must either:

  • Return a proper Gulp stream from the task function, e.g.: return gulp.src().pipe(gulp.dest());
  • Return a valid Promise (thenable object), e.g.: return del(); or return new Promise();
  • Call a callback function passed to it, e.g.: callback();

WARNING: If your task function is synchronous — please read the section below!

Using root directory tasks

Starting from version 1.1.0 you can place index.js inside of the task directories. The actual task, registered with Gulp will have the name of the directory itself, e.g.: scripts/build/index.js will become: scripts:build.

The index.js, placed in the root of tasks directory, will be registered as a default task.

Passing data to the task function

If you need to pass something to the task function from your gulpfile you can use globals.

Define your custom properties on the global object:

// gulpfile.js

global.SOURCES_BASE_PATH = __dirname + '/src';

And then use it in your task module:

// gulp/tasks/styles/build.js
module.exports = gulp =>
  gulp.src(global.SOURCES_BASE_PATH + '/styles/*.scss')
    .pipe(compass())
    .pipe(gulp.dest('…'))
;

Synchronous tasks

If you are using synchronous tasks, i.e. tasks which execute synchronously without returning streams, promises or accepting callbacks, you will have to use one of the workarounds specified below:

1). The simplest method is to use nativeTask functionality, here's the example of the module with native task synchronous function:

module.exports = {
  nativeTask: function () {
    console.log('This is the synchronous native task without a callback!');
  }
};

2). You should call a callback explicitly:

module.exports = function (gulp, callback) {
  console.log('This is the synchronous native task with explicit callback!');
  callback(); // Don't forget this, otherwise task will never finish!
};

However, if config.passCallback == false you won't be able to use the second method.

These workarounds must be used due to architectural limitation of this module integration with orchestrator. Please see the issue #9: Synchronous tasks without callback don't finish for more technical details.

Changelog

Please see the changelog for list of changes.

Feedback

If you have found a bug or have another issue with the library — please create an issue.

If you have a question regarding the library or it's integration with your project — consider asking a question at StackOverflow and sending me a link via E-Mail. I will be glad to help.

Have any ideas or propositions? Feel free to contact me by E-Mail.

Cheers!

Support

If you like this library consider to add star on GitHub repository.

Thank you!

License

The MIT License (MIT)

Copyright (c) 2016-2020 Slava Fomin II

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

gulp-require-tasks's People

Contributors

7studio avatar slavafomin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

gulp-require-tasks's Issues

Unexpected token ...

Hi,

I've got this error :
/node_modules/gulp-require-tasks/index.js:93
taskNameParts.push(...pathInfo.dir.split(path.sep));
^^^

SyntaxError: Unexpected token ...
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:373:25)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)

Do you know what can be the error ?

Thank you

Possible to retrieve values from dependencies?

Using the following syntax:

const compass = require('compass');
 
module.exports = {
  dep: ['styles:clean', 'icons:build'],
  fn: function (gulp, callback) {
    return gulp.src('...')
      .pipe(compass())
      .pipe(gulp.dest('...'))
    ;
  }
};

is there a way to declare a variable or an object in the dependencies and have it come through to the function being declared afterwards?

Here's my code for example. I am trying to compile templates from assemble.io.

gulpfile.js

const gulp = require('gulp');
require('gulp-require-tasks')();

gulp.task('build', [
	'assemble'
]);

gulp.task('default', ['build']);

assemble-load.js

'use strict';

module.exports = (gulp, callback) => {
	const path = require('path');
	const assemble = require('assemble')();

	assemble.helper(require(path.join(__dirname, '/../app/assemble/helpers/helpers.js')));

	assemble.partials([
		path.join(__dirname, '/../app/assemble/includes/*.hbs'),
		path.join(__dirname, '/../app/assemble/modules/*.hbs'),
		path.join(__dirname, '/../app/assemble/partials/*.hbs')
	]);
	assemble.layouts(path.join(__dirname, '/../app/assemble/layouts/*.hbs'));
	assemble.data(path.join(__dirname, '/../app/assemble/fixtures/*.json'));
  	assemble.pages(path.join(__dirname, '/../app/assemble/*.hbs'));

	return assemble;

	callback();
}

assemble.js

'use strict';

module.exports = {
	dep: ['assemble-load'],
	fn: function (gulp, callback) {
		
		const path = require('path');		
		const assemble = require('assemble')();
		const extname = require('gulp-extname');

		return assemble.toStream('pages')
			.pipe(assemble.renderFile())
			.pipe(extname())
			.pipe(assemble.dest('../app'));

	}
}

I had this working earlier in a more combined syntax, I'm just trying to get it into this fancy syntax, so I know my paths and such are correct. Also, outputting assemble to the console in assemble-load.js I can see all my templates and partials in the object. If I output assemble in assemble.js, it's just an empty object.

I'm not super solid on ES6 so I would appreciate code examples over vocabulary words. Thanks!

Multiple tasks in a single file?

Can you still have multiple tasks in the same file? Sometimes you want to have multiple tasks in one file because they might all use some shared variables declared at the top of the file, and the tasks might be logically-related so it makes sense to have them in the same file.

Share configuration variables across all task files

how does one pass in configurations stored in some variable?

Vars do not seem to be shared across multiple gulpjs files, but I store them in one place to avoid repeating things and also to keep the piping clean.

Sub-task triggers parent task

tasks/
    build/
        index.js
        watch/
            index.js

Tasks: build, build:watch

When running build:watch I'm not expecting build to run.
But they both run in parallel.

Also if I remove build/index.js there's an error: Task 'build' is not in your gulpfile

I think sub-tasks should be independent from parent tasks,
and users should explicitly run both if they want, instead of implicit run in parallel.
Eg. user may want to run parent-child in sequence, or do not run parent at all (my case).

In my case both build and build:watch tasks share same build/ folder,
but build:watch is not extension of the build, but rather - separate version of it.

What do you think? Is that conscious behavior or just a bug?

arguments is an empty object in on.('finish') callback

Seems that the arguments is empty in the on finish callback, or am I doing something wrong here?

var chug = require('gulp-chug');

module.exports = function (gulp, arguments, callback) {
    return gulp.src( arguments.path + 'gulpfile.js' )
        .pipe( chug( {
                    tasks: [ 'build' ],
                    args:   [ '--ip=' + arguments.ip, '--api=' + arguments.api , '--https=' + arguments.https]}) )
        .on('finish', function() {
            console.log(arguments) //arguments is {} here (empty)
            gulp.src([arguments.path + '/dist/**/*'])
            .pipe(gulp.dest('a-destination-name'));
        });
};

Register tasks with the name of directories

Hi Slava,

First of all, thank you very much for your useful gulp plugin :D

I would like to suggest a new feature.
Here is my case:

I have these sub-directories to structure my tasks:

gulp/
  install/
    task1.js
    task2.js
  process/
  	task1.js
    task2.js
    task3.js
  build/

and this gulpfile.js:

var gulp = require('gulp');
var tasksLoader = require('gulp-require-tasks');
var runSequence = require('run-sequence');

tasksLoader({
    path: process.cwd() + '/gulp/tasks',
    gulp: gulp
});

gulp.task('install', ['install:task1', 'install:task2']);

gulp.task('process', function(done) {
    runSequence(
        ['process:task1'],
        ['process:task2'],
        ['process:task3'],
        done
    );
});

It could be very very useful if we could find a way to register tasks with the same
name than directories without creating them in the gulpfile.js or having files
with these names into the gulp/ directory.

I thought that having an index.js in the directories could register a gulp task with the name
of these directories.

Example:

gulp/
  install/
  	index.js
    task1.js
    task2.js
  process/
  	index.js
  build/

will register these tasks:

  • install
  • install:task1
  • install:task2
  • process

What do you think about this idea?

I would be happy to help you through a PR if you want to.
Xavier.

Load tasks from multiple directories

Is it somehow possible to use multiple path directories for example with glob patterns?
Lets say I have multiple modules with their own tasks directory.

taskLoader({
    gulp: gulp,
    path: __dirname + '/modules/**/tasks',
    passCallback: false
});

Synchronous tasks without callback don't finish

In line 55 function taskFunction (callback) { ... } defines a parameter (callback) that conflicts with orchestrator's runTask which relies in Function.length and interprets that the task terminates only after the callback is called.

In this sense, the config argument passCallback lacks purpose and the tasks written in separate files are obliged to function with a callback parameter or they won't finish.

Add dependencies to package.json

Installing gulp-require-tasks will not install the required dependencies needed by gulp-require-taks (e.g. require-directory).

Please consider adding them to package.json so an user will not need to install the missing dependencies manually.

Question: Alternative syntax for dependencies

Hi there,

Thanks a lot for your gulp module, it works really cool and makes everything a lot more readable.
One question though: if a task has no dependencies the format is really compact like your sample:

module.exports = function (gulp, callback) {
  return gulp.src('...')
    .pipe(compass())
    .pipe(gulp.dest('...'))
  ;
};

But if there is a dependency one has to switch to the module as object syntax. Would it be possible to support a syntax similar to:

module.dependencies = ['task1, 'task2']
module.exports = function (gulp, callback) {
  return gulp.src('...')
    .pipe(compass())
    .pipe(gulp.dest('...'))
  ;
};

This looks somehow a little bit cleaner than the module as object way. Though really don't know if this is possible. Thanks for your thoughts on this.

The path option documentation is not clear

The available information for the path option is not clear enough. The default value is process.cwd() + '/gulp-tasks' and not ./gulp-tasks.

When trying to import tasks from a relative directory, gulp will throw an error because it looks for a directory that is relative to the module directory and not the project root where gulpfile.js is located.

To reproduce the issue, try to import tasks from a relative path, like:

require('gulp-require-tasks')({
  path: './my-gulp-tasks'
});

__dirname + '/tasks' is not default value of path parameter

First of all thank you for this useful module.

I've noticed that when calling

gulpRequireTasks({});

default path parameter resolves to node_modules/gulp-require-tasks/tasks folder. This is not too big of an issue since we can initialize it with

gulpRequireTasks({
  // Pass any options to it. Please see below.
  path: __dirname + '/tasks' // This is default
});

But still I think it would make more sense to default it __dirname + '/tasks' . Also "// this is default" comment is misleading.

Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.