gulp sass 出错后显示错误提示到页面,不退出进程

0. 效果

clipboard.png

1. sass 或 less 编译出错后不退出

需要监听 sass 的error事件

...
.pipe(sass().on('error', notify))
...
function notify(err) {
  // prevent gulp process exit
  this.emit('end');
}

2. 将编译的错误信息显示到页面

受到compass 启发,将出错信息利用 body:before { content: } 输出

完整的代码如下

function notify(err) {
  // prevent gulp process exit
  this.emit('end');

  var title = err.plugin + ' ' + err.name;
  var msg = err.message;
  // print error to stderr
  process.stderr.write(title + '\n ' + err.messageFormatted);
  // system notification
  notifier.notify({
    title: title,
    message: msg,
    sound: 'Morse'
  });

  // show sass compile error on page
  // get dest file from error file
  var errFile = err.relativePath.replace(/\bscss\b/g, 'css');
  if(err.file != 'stdin') { // error occurred in a partial file (via @import)
    errFile = 'static/css/app.css'; // show error in a default file
  }
  var errContent = msg.replace(/\n/g, '\\A '); // replace to `\A`, `\n` is not allowed in css content
  // http://codepen.io/scottkellum/pen/YXbpeQ
  fs.writeFile(errFile, util.format('body:before { background: #fff; padding: 15px;' +
    'position: fixed; left: 0; right: 0; z-index: 99999;' +
    'overflow-y: auto; border-bottom: solid 1px #eee; color: #C93900;' +
    'white-space: pre; font-family: monospace;' +
    'content: \'%s\';}', errContent)
  );
}
// usage
gulp.task('sass', function () {
  return gulp.src('./sass/**/*.scss')
    .pipe(sass().on('error', notify))
    .pipe(gulp.dest('./css'));
});

3. 参考

Debug Sass in Codepen

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值