Divide gulp-file into several files

javascript node.js gulp

120 观看


0 作者的声誉

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:

├── css_tasks.js
└── js_tasks.js

And then use require-dir in gulpfile.js:


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:

├── 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 */


/* js_tasks.js: */

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

So, how can I do it?

作者: user9062413 的来源 发布者: 2017 年 12 月 27 日

回应 (1)


5096 作者的声誉


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:

├── 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


// 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.

作者: The Reason 发布者: 27.12.2017 07:24