Webpack crashes gulp watch when it fails to compil

2019-07-10 04:40发布

问题:

I have a gulp-watch task running which is compiling my front-end application. When I have a typescript error (be it just because I hit save too early) the whole process crashes and I have to restart it manually. I'd like webpack and the typescript compiler to just report errors, as long as they run in watch mode, instead of crashing the process.

My gulp task to compile my typescript application with webpack:

gulp.task('scripts', function (callback) {
    var isWatching = watchEnabled;

    var webpackOptions = {
        resolve: { extensions: ['', '.ts'] },
        watch: watchEnabled,
        module: {
            preLoaders: [{ test: /\.ts$/, exclude: /node_modules/, loader: 'tslint-loader' }],
            loaders: [{ test: /\.ts$/, exclude: /node_modules/, loader: 'awesome-typescript-loader' }]
        },
        output: { filename: 'app.js' },
        tslint: { emitErrors: !watchEnabled } // tslint crashes gulp when emitting errors, so don't do it while watch is enabled
    };

    if (debugEnabled) {
        webpackOptions.devtool = 'inline-source-map';
    }

    var webpackChangeHandler = function (err, stats) {
        if (err) {
            console.error('Webpack', err);
        }
        $.util.log(stats.toString({
            colors: $.util.colors.supportsColor,
            chunks: false,
            hash: false,
            version: false
        }));

        if (isWatching) {
            isWatching = false;
            callback();
        }
    };

    return gulp.src('./Scripts/application/app.ts')
      .pipe(webpack(webpackOptions, null, webpackChangeHandler))
      .pipe($.if(!debugEnabled, $.uglify()))
      .pipe($.if(!watchEnabled, $.rev()))
      .pipe(gulp.dest(tmpFolder + 'Content/'));
});

When compiling in CI server it is good that compile and tslint errors crash the process and the CI server reports an error.

However when developing it is quite annoying. I've solved the tslint problem, by turning off emitErrors as long as gulp watch and webpack watch are running. But for typescript compilation I'm not sure how to do it.

Is this an option I should find on webpack or the awesome-typescript-loader?

I didn't find anything fitting this problem on the awesome-typescript-loader github repo, which makes me think that I should enable some webpack option, but which one?

回答1:

had the same problem. this worked for me

var wp = webpack(webpackOptions, null, webpackChangeHandler);
// can bind error to console, but it will be duplicated with webpackChangeHandler err
// wp.on('error', console.error.bind(console));
wp.on('error', function() {});

return gulp.src('./Scripts/application/app.ts')
      .pipe(wp)
      .pipe($.if(!debugEnabled, $.uglify()))
      .pipe($.if(!watchEnabled, $.rev()))
      .pipe(gulp.dest(tmpFolder + 'Content/'));