2

我创建了一个简单的 Gulp 任务来检查我的 ES6 文件中的更改。我想转换它们并在出现问题时显示错误消息。

正在显示错误屏幕。但是,当一切都成功时,我想显示不同的信息。我尝试了该.on('end')方法,但是当出现一些错误时也会调用该方法。

我当前的 Gulpfile 如下所示:

const gulp = require('gulp');
const babel = require('gulp-babel');
const uglify = require('gulp-uglify');
const pump = require('pump');
const imagemin = require('gulp-imagemin');
const sass = require('gulp-sass');
const DISTRIBUTION_PATH = 'public/theme/js/app';
const plumber = require('gulp-plumber');
const gutil = require('gulp-util');
const clear = require('clear');

gulp.task('transpile', () =>
    gulp.watch('theme/js/**/*.js', () => {
        return gulp.src('theme/js/**/*.js')
            .pipe(plumber())
            .pipe(babel({
                presets: ['es2015'],
                plugins: [
                    'transform-object-rest-spread'
                ]
            }))
            .on('error', err => {
                clear();
                gutil.log(gutil.colors.red('[Compilation Error]'));
                gutil.log(err.fileName + ( err.loc ? `( ${err.loc.line}, ${err.loc.column} ): ` : ': '));
                gutil.log(gutil.colors.red('error Babel: ' + err.message + '\n'));
                gutil.log(err.codeFrame);
            })
            .pipe(gulp.dest(DISTRIBUTION_PATH));
    })
);

任何想法如何实现这一目标?

4

2 回答 2

5

答案可能有点晚,但对于像我这样的 Google 员工,我已经创建了一个解决方案。我添加了一个布尔值 isSuccess 来确定转译是否成功。如果出现错误,isSuccess 将变为 false,并且消息不会“结束”显示。

const gulp = require('gulp');
const babel = require('gulp-babel');
const uglify = require('gulp-uglify');
const pump = require('pump');
const imagemin = require('gulp-imagemin');
const sass = require('gulp-sass');
const DISTRIBUTION_PATH = 'public/theme/js/app';
const plumber = require('gulp-plumber');
const gutil = require('gulp-util');
const clear = require('clear');

gulp.task('transpile', () =>
    gulp.watch('theme/js/**/*.js', () => {
        let isSuccess = true;
        return gulp.src('theme/js/**/*.js')
            .pipe(plumber())
            .pipe(babel({
                presets: ['es2015'],
                plugins: [
                    'transform-object-rest-spread'
                ]
            }))
            .on('error', err => {
                isSuccess = false;
                clear();
                gutil.log(gutil.colors.red('[Compilation Error]'));
                gutil.log(err.fileName + ( err.loc ? `( ${err.loc.line}, ${err.loc.column} ): ` : ': '));
                gutil.log(gutil.colors.red('error Babel: ' + err.message + '\n'));
                gutil.log(err.codeFrame);
            })
            .pipe(gulp.dest(DISTRIBUTION_PATH))
            .on('end', ()=> {
                if( isSuccess )
                    console.log('Yay success!');
            });
    })
);
于 2017-03-07T20:27:03.880 回答
-1

你可以做

.on('error', () => {
   // some log or code for failure
 })
.on('end', () => {
   // some log or code for success
 });
于 2020-10-09T10:33:05.890 回答