【问题标题】:Gulp wait until other function is doneGulp 等到其他功能完成
【发布时间】:2017-01-21 11:24:14
【问题描述】:

我正在使用 gulp 构建带有浏览器同步的 html/css/ts 以进行 livereload。问题是在第一次构建时,构建 html 比 ts build 快得多,所以当 browser-sync 运行时,它无法加载已编译的 JavaScript。

这是我的 gulpfile.js:

const gulp = require('gulp');
const gutil = require('gulp-util');
const merge = require('merge-stream');
const watchify = require('watchify');
const tsify = require('tsify');
const source = require('vinyl-source-stream');

const browserSync = require('browser-sync').create();


function swallowError (error) {
    console.log(error.toString());
    this.emit('end');
}

function buildHtml() {
    return gulp.src('./src/html/index.html')
    .pipe(gulp.dest('./build'));
}

function buildCss() {
    return gulp.src('./src/css/app.css')
    .pipe(gulp.dest('./build'))
    .pipe(browserSync.stream());
}

function buildScript() {
    let opts = Object.assign({}, watchify.args, { debug: true });
    let b = watchify(opts)
    .add('./src/ts/index.tsx')
    .on('update', bundle)
    .on('log', gutil.log)
    .plugin(tsify, {
        jsx: 'react'
    });

    function bundle() {
        return b.bundle()
        .on('error', swallowError)
        .pipe(source('index.js'))
        .pipe(gulp.dest('./build'));
    }

    return bundle();
}

gulp.task('default', () => {
    browserSync.init({
        server: './build'
    });


    gulp.watch('./src/html/**.html', buildHtml);
    gulp.watch('./src/css/**.css', buildCss);

    gulp.watch('./build/index.html').on('change', browserSync.reload);
    gulp.watch('./build/index.js').on('change', browserSync.reload);

    return merge([
        buildHtml(),
        buildScript(),
        buildCss()
    ]);
});

您可以看到构建每个资源的函数,buildHtml、buildScript、buildCss。他们工作得很好,但在这种情况下,我不知道如何在 buildHtml 和 merge-stream 之后执行 buildScript。

您可以看到 4 个观看代码,当然,这些代码用于 livereload,观看 build/index.js 在首次构建时不起作用。我的意思是在第一次构建时,将创建第一个构建目录并且 html 也将在那里,但尚未创建 index.js。而此时,浏览器同步将激活,运行此应用程序但脚本不存在,所以它失败了。编译脚本后,浏览器同步不会重新加载,看起来生成的新文件根本没有触发 onchange 事件。

这将解决用 F5 刷新网站,或者只是重新启动 gulp,但我想解决这个问题。任何建议都会非常感激!!

【问题讨论】:

  • gulp.task("default", gulp.series (buildScript, buildCss,buildHtml, () => etc.));

标签: gulp


【解决方案1】:

我通过在编译完成后运行 browser-sync 解决了这个问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-03
    • 2018-06-29
    • 1970-01-01
    • 1970-01-01
    • 2013-03-30
    • 2016-07-09
    • 1970-01-01
    相关资源
    最近更新 更多