簡體   English   中英

如何處理吞噬中的錯誤。 注意防止錯誤報告

[英]How handle watchify errors in gulp. Watchify prevent error from being reported

當我在瀏覽器捆綁程序中包含watchify插件並且出現編譯時錯誤時,不會記錄該錯誤。

const gulp        = require('gulp');
const browserify  = require('browserify');            //js bundler
const watchify    = require('watchify');              //allows incremental bundling
const hbsfy       = require('hbsfy');                 //precompiles hbs files
const babelify    = require('babelify');              //ES2015 to ES5
const source      = require('vinyl-source-stream');   //Gulp and NodeJS stream interop. Use conventional text streams at the start of your gulp or vinyl pipelines, making for nicer interoperability with the existing npm stream ecosystem.
const buffer      = require('vinyl-buffer');          //Convert streaming vinyl files to use buffers. Usually used with vinyl-source-stream and gulp-sourcemaps
const uglify      = require('gulp-uglify');           //uglifyjs (js minimalizer) plugin for gulp (would be nice to use uglyfyjs directly)
const sourcemaps  = require('gulp-sourcemaps');       //generate source maps when tranforming js or css 
const gutil       = require('gulp-util');             //utlis for gulp, e.g. console logging

gulp.task("watch-js", function(done){
    var b = browserify({
        entries: 'main.js',
        debug: true,
        cache: {},
        packageCache: {},
      });
    b.external(config.vendorJsLibs);
    b.transform(hbsfy);
    b.transform(babelify, { presets: ['es2015'] });

    b.plugin(watchify); //when I comment this, errors are reported
    b.on('error', function(err){
       gutil.log(err.toString());
       this.emit('end');
       done();
    });
    compileJs(b, 'app.js');
    b.on('update', function(evt){
        gutil.log('watchify update '+ evt);
        compileJs(b, 'app.js');
    });    
});     

function compileJs(bundler, bundleFileName){
    return bundler.bundle()
        .pipe(source(bundleFileName))
        .pipe(buffer())
        .pipe(sourcemaps.init({loadMaps: true}))
            // Add transformation tasks to the pipeline here.
            .pipe(uglify())
            .on('error', function(error){
                gutil.log(error);
                this.emit('end');
            })
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest(dest + '/scripts'));
}

捆綁包中沒有任何錯誤處理程序,這就是節點崩潰並打印堆棧跟蹤的原因。 這是一種安全機制,可確保處理錯誤事件或中止執行。

Watchify 偵聽捆綁程序上的錯誤事件以了解內部邏輯。 這滿足了節點錯誤處理要求。

在您的代碼中,您應該偵聽b.bundle()返回的流上的錯誤事件。 以下代碼可以解決問題:

function compileJs(bundler, bundleFileName){
    return bundler.bundle()
        .on('error', gutil.log)
        ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM