Search code examples
javascriptnode.jsgulp

Divide gulp-file into several files


I want to divide one big gulp-file into several files.
Some of this files is supposed to contain gulp-tasks, others – raw functions, third files – both.
How can I do it?

I've tried to create directory with a few files, some like that:

gulpfile.js
gulp/
├── css_tasks.js
└── js_tasks.js

And then use require-dir in gulpfile.js:

require('require-dir')('./gulp');

It works well, but this method allows to use only tasks from required directory.

But this is not enough.
In addition, I want to use raw functions from another files, some like that:

gulpfile.js
gulp/
├── common_methods.js
├── css_tasks.js
└── js_tasks.js

And use it in a this way:

/* css_tasks.js: */

gulp.task('some_css_task', function() {
   var foo = someCommonMethod();
   /* task stuff */
})

and

/* js_tasks.js: */

gulp.task('some_js_task', function() {
   var boo = anotherCommonMethod();
   /* task stuff */
})

So, how can I do it?


Solution

  • According to require-dir module, it returns an object based on your directory structure.

    {
      a: require('./a'),
      b: require('./b')
    }
    

    So i suggest creating folders for your js & css "gulp-task-files". So the structure can be the next:

    gulp/
    ├── common_methods.js
    ├── css/index.js
    └── js/index.js
    

    Then in your gulpfile you should require css & js folder separately like:

    const js = require('require-dir')('./gulp/js');
    const css = require('require-dir')('./gulp/css');
    

    It will allow you to have common_methods.js file which can be shared between these (js & css) task-folders & common_methods.js will not be exported via require-dir

    UPDATE

    // common_methods.js
    function method1(){}
    function method2(){}
    
    module.exports = {
      foo: method1,
      baz: method2
    }
    
    // js/index.js
    const foo = require('../common_methods').foo;
    
    // css/index.js
    const baz = require('../common_methods').baz;
    

    Hope it make sense.