从单独的gulp文件导入/读取变量

RGL*_*LSV 7 javascript fs gulp

我想将我的gulpfile.js assetssrc变量拆分成单独的文件,以便我可以更好地管理它们.例如:

....

var scripts = ['awful.js', 'lot.js', 'of.js', 'js.js', 'files.js']

....(somewhere down the line)

gulp.task('vendorjs', function() {
    return gulp.src(scripts)

        .pipe(concat('vendor.js'))
        .pipe(rename({suffix: '.min'}))
        .pipe(uglify())
        .pipe(gulp.dest(paths.root + 'dist'))
        .pipe(notify({ message: 'vendorjs task completed' }));
});
Run Code Online (Sandbox Code Playgroud)

所以我真的很感兴趣,如果有一种方法可以实际移动到一个单独的文件scripts变量,并能够从中访问它gulpfile.js.

我一直在寻找类似的东西:

require("fs").readFile('gulp/test.js', function(e, data) {
   //(test.js would be the file that holds the scripts var)
});
Run Code Online (Sandbox Code Playgroud)

Howerver虽然它确实读取了文件的内容,但我仍然无法从中访问它gulpfile.js.任何提示或想法都非常感谢.

Sve*_*ung 11

Node.js允许您使用导入其他文件require().它支持三种类型的文件:

  • JSON文件.请参阅DavidDomain的答案.
  • 二进制Node.js插件.对您的用例没用.
  • JavaScript文件.那正是你想要的.

对于JavaScript文件,返回的值require()module.exports在导入的文件中分配 的值.

所以对于你的用例:

一饮而尽/ test.js

var arrayOfFiles = ["awful.js", "lots.js"];
arrayOfFiles.push("of.js");
arrayOfFiles.push("js.js");
arrayOfFiles.push("files.js");
for (var i = 0; i < 10; i++) {
  arrayOfFiles.push("some_other_file" + i + ".js");       
}

module.exports = {
  scripts: arrayOfFiles
};
Run Code Online (Sandbox Code Playgroud)

gulpfile.js

var test = require('gulp/test.js');

gulp.task('vendorjs', function() {
  return gulp.src(test.scripts)
    .pipe(concat('vendor.js'))
    .pipe(rename({suffix: '.min'}))
    .pipe(uglify())
    .pipe(gulp.dest(paths.root + 'dist'))
    .pipe(notify({ message: 'vendorjs task completed' }));
});
Run Code Online (Sandbox Code Playgroud)