Gulp -使用少量JS文件连接watchify的结果

Gulp - concat result of watchify with few JS files

本文关键字:连接 文件 watchify 结果 JS Gulp      更新时间:2023-09-26

我有一个使用watchify的JS应用程序。

所以,我想把watchify命令的结果与其他一些javascript文件连接起来,这些文件往往是全局的(jQuery等)。这是我的Javascript watchify命令。

var source = require('vinyl-source-stream');
var gulp = require('gulp');
var gutil = require('gulp-util');
var browserify = require('browserify');
var reactify = require('reactify');
var watchify = require('watchify');
var notify = require("gulp-notify");
var scriptsDir = './scripts';
var buildDir = './build';

function handleErrors() {
  var args = Array.prototype.slice.call(arguments);
  notify.onError({
    title: "Compile Error",
    message: "<%= error.message %>"
  }).apply(this, args);
  this.emit('end'); // Keep gulp from hanging on this task
}

function buildScript(file, watch) {
  var props = {entries: [scriptsDir + '/' + file]};
  var bundler = watch ? watchify(props) : browserify(props);
  bundler.transform(reactify);
  function rebundle() {
    var stream = bundler.bundle({debug: true});
    return stream.on('error', handleErrors)
    .pipe(source(file))
    .pipe(gulp.dest(buildDir + '/'));
  }
  bundler.on('update', function() {
    rebundle();
    gutil.log('Rebundle...');
  });
  return rebundle();
}

gulp.task('build', function() {
  return buildScript('main.js', false);
});

gulp.task('default', ['build'], function() {
  return buildScript('main.js', true);
});

这是我用来附加javascript文件的任务。

return gulp.src([
  './bower_components/jquery/dist/jquery.min.js',
  './bower_components/redactor-wysiwyg/redactor/redactor.js',
  './build/main.js' // output of `gulp build`.
]).pipe(concat('application.js'))
  .pipe(gulp.dest('./public/'));

如何使用一个函数buildScript连接这些javascript文件

关键是nodejs流有一个end事件。

function rebundle() {
  var stream = bundler.bundle({debug: true});
  stream.on('end', function() { gulp.start('everything_you_want') }); 
  return stream.on('error', handleErrors)
    .pipe(source(file))
    .pipe(gulp.dest(buildDir + '/'));
}