I have one npm package containing several files with several gulp task definitions.
What I want is in the main gulpfile, be able to copy these gulp files (from the package) and execute the gulp tasks defined in them.
Follows an example:
JavaScript
x
20
20
1
const gulp = require('gulp');
2
const fs = require('fs');
3
const path = require('path');
4
5
const gulpFolder = path.join(__dirname.replace('gulpfile.js', ''), 'src', 'generated-code', 'gulp');
6
7
const cleanGulpFiles = (callback) => { }
8
9
const copyGulpFiles = (callback) => {
10
gulp.src(`${nodeModulesFolder}/@primavera/client-app-core/gulp/**/*`)
11
.pipe(chmod(666))
12
.pipe(gulp.dest(gulpFolder));
13
callback();
14
}
15
16
exports.debug = gulp.series(
17
cleanGulpFiles,
18
copyGulpFiles,
19
require('../src/generated-code/gulp/gulp.debug'));
20
The problem is: When I try to execute gulp debug
, it is retrieved an error saying require('../src/generated-code/gulp/gulp.debug')
does not exists. And it is right because this file will be only available when the task copyGulpFiles
is done.
Anyone knows a workaround to do what I want to accomplish?
Advertisement
Answer
The only workaround that I found was to combine fs.readFileSync and eval functions in order to read the gulp file content as a string and then evaluate that code in run time:
JavaScript
1
26
26
1
const gulp = require('gulp');
2
const fs = require('fs');
3
const path = require('path');
4
5
const gulpFolder = path.join(__dirname.replace('gulpfile.js', ''), 'src', 'generated-code', 'gulp');
6
7
const cleanGulpFiles = (callback) => { }
8
9
const copyGulpFiles = (callback) => {
10
gulp.src(`${nodeModulesFolder}/@primavera/client-app-core/gulp/**/*`)
11
.pipe(chmod(666))
12
.pipe(gulp.dest(gulpFolder));
13
callback();
14
}
15
16
const executeGulpFiles = (callback) => {
17
const fileContent = fs.readFileSync('../src/generated-code/gulp/gulp.debug');
18
const contentEvaluated = eval(fileContent);
19
contentEvaluated(callback);
20
}
21
22
exports.debug = gulp.series(
23
cleanGulpFiles,
24
copyGulpFiles,
25
executeGulpFiles);
26