Gulp plumber не работает

Gulp.watch: ловим ошибки правильно

Во всех современных системах сборки фронтенда есть режим watch , при котором запускается специальный демон для автоматической пересборки файлов сразу после их сохранения. Также он есть и gulp.js, но с некоторыми особенностями, делающими работу с ним немного сложней. Работа gulp.js основана на обработке файлов как потоков данных (streams). И ошибки в потоках не всегда можно перехватить, а когда ошибка случается, то будет выброшено неперехваченное исключение и процесс завершится.

Чтобы этого не происходило, и watcher мог игнорировать отдельные ошибки и запускаться снова и снова при сохранении файлов, в gulp нужно сделать несколько дополнительных настроек, о которых и расскажется в этой статье.

Что происходит?

Для начала разберемся что происходит и почему же watcher иногда падает. При написании плагина к gulp рекомендуется испускать событие error при возникновении ошибок во время работы плагина. Но nodejs-потоки, на которых основана система сборки, не позволяют ошибкам оставаться незамеченными. В случае, если на событие error никто не подписался, выбросится исключение, чтобы сообщение точно достигло пользователя. В результате, при работе с gulp разработчики часто видят такие ошибки

При применении Continious-Integration (CI), когда на каждый коммит запускаются автоматические проверки, это может быть и полезным (сборка провалилась, билд не собрался, ответственные получат письма). Но вечно падающий watcher в локальной разработке, который нужно постоянно перезапускать – это большая неприятность.

Что делать?

В интернете можно найти вопросы этой теме как на stackoverflow, так и на тостере. В ответах на вопросы предлагают несколько популярных решений.

Можно подписаться на событие error :

Можно подключить плагин gulp-plumber, который не только подпишется на error для одного плагина, но и автоматически сделает это и для всех последующих плагинов, подключенных через pipe:

Почему так не надо делать

Несмотря на то, что проблема выглядит как решенная, это не так. Теперь ошибки сборки перехватываются, мы получаем в консоль сообщения об этом, запущенный демон-watcher не падает, но у нас теперь есть новая проблема.

Допустим у нас есть CI-сервер, где идет сборка наших скриптов для выкладки. Чтобы наша сборка работала вместе с watch, мы применили одно из решений выше. Но теперь оказывается, что при ошибках в сборке наш билд все равно отмечается как успешный. Команда gulp всегда завершается с кодом 0. Получается, для CI-сборки нам не нужно проглатывать ошибки. Можно добавлять свой обработчик ошибок только для watch режима, но это усложнит описание сборки и повысит шансы допустить ошибку. К счастью, есть решение, как настроить сборку одинаково, но при этом поддержать работу и в режиме билда и в режиме watch.

Решение

На самом деле gulp пытается слушать ошибки в потоках файлов. Но из-за того, что обычно последним идет вызов gulp.dest() , записывающий результат на диск, а ошибки случаются в промежуточных плагинах, то ошибка не достигает конца цепочки, поэтому gulp о ней не узнает. Например рассмотрим такую цепочку:

Читайте также:  У хорошего мужа жена не работает цитаты

В отличие от, например, promise, ошибки в потоках не распространяются дальше по цепочке, их нужно перехватывать в каждом потоке отдельно. По этому поводу есть pull-request в io.js, но в нынешних версиях передать ошибку в конец цепочки не получится. Поэтому gulp не может перехватить ошибки промежуточных потоках и нам это нужно делать самостоятельно.

Зато gulp в качестве описания task принимает не только функцию, возвращающую поток, но и обычную callback-style функцию, как и многие API в node.js. В такой функции мы сами будем решать, когда задача завершилось с ошибкой, а когда успешно:

Такое описание сборки выглядит немного больше, потому что мы теперь делаем часть работы за gulp, но теперь мы ее делаем правильно. А если написать себе вспомогательную функцию, вроде такой, то разница будет практически незаметна:

Зато мы получим правильные сообщения в консоли как во время разработки и пересборке при сохранении, так и на CI-сервере во время билда.

Источник

И снова.. Почему Gulp 4 не работает?

Подскажите, пожалуйста. Почему это не работает?
Может кто-то взять к себе и протестировать?
https://github.com/KononovD/kononovD.github.io/tre.
тут сам gulpfile.js и package.json

Ошибка следующая
[22:37:09] Using gulpfile

\Desktop\testGulp\gulpfile.js
[22:37:09] Starting ‘default’.
[22:37:09] Starting ‘build’.
[22:37:09] Starting ‘clean:build’.
[22:37:09] Finished ‘clean:build’ after 2.01 ms
[22:37:09] Starting ‘html:build’.
[22:37:09] Finished ‘html:build’ after 13 ms
[22:37:09] Starting ‘scss:build’.
[22:37:09] ‘scss:build’ errored after 4.53 ms
[22:37:09] TypeError: dest.on is not a function
at DestroyableTransform.Readable.pipe (C:\Users\я\Desktop\testGulp\node_modules\readable-stream\lib\_stream_readable.js:564:8)
at DestroyableTransform.pipe2 (C:\Users\я\Desktop\testGulp\node_modules\gulp-plumber\index.js:72:14)
at C:\Users\я\Desktop\testGulp\gulpfile.js:82:10
at taskWrapper (C:\Users\я\Desktop\testGulp\node_modules\undertaker\lib\set-task.js:13:15)
at bound (domain.js:395:14)
at runBound (domain.js:408:12)
at asyncRunner (C:\Users\я\Desktop\testGulp\node_modules\async-done\index.js:55:18)
at process._tickCallback (internal/process/next_tick.js:61:11)
[22:37:09] ‘build’ errored after 23 ms
[22:37:09] ‘default’ errored after 26 ms

Мне почему-то кажется, что все дело в автопрефиксере..

И еще может кто объяснить в чем разница 2х наблюдателей? Они в самом низу, первый (закомментированный) не просит модуль «gulp-warch», а 2й просит.. В чем разница?
Спасибо.

Источник

Error handling with gulp-notify and gulp-plumber

I want to display a notification when:
1. An error occurs
2. When the script was successfully executed

All notifications are actually working but the success notification is always displayed, even when there is an error.

How can I make sure the success notification is only displayed when no errors have occurred?

This is my current task:

2 Answers 2

I encountered the same issue and what worked for me was gulp-if and a custom error handler. Basically, I set errorFree = false when an error is thrown then at the end when it’s time to show the success message I use gulp-if to determine if notify() gets called or not.

Читайте также:  Не работает тональный режим

Working with your gulpfile:

In my gulpfile I actually wrap each step in gulp-if so that the stream stops processing. (I haven’t found a way to stop the stream without killing the process, which defeats the purpose of watch IMO.)

I’ve run into a very similar situation recently and the code Jeffwa provided helped me make it work; but I’m compiling and merging several files, and was having issues with the error and the «success» notification being fired.

In case someone else run into a similar situation the solution I found was creating a function on the success notification and there returning either false if there was an error or the information object. This is the code example.

Not the answer you’re looking for? Browse other questions tagged gulp or ask your own question.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.10.15.40479

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Not working with gulp-sass #32

Comments

realph commented May 20, 2015

My terminal still returns an error and breaks my task when there’s an error in my Sass. This is what my task looks like:

Any idea why it keeps breaking? Any help is appreciated. Thanks in advance!

The text was updated successfully, but these errors were encountered:

JoshLipps commented May 22, 2015

floatdrop commented May 27, 2015

Good news — there is nothing wrong in gulp-sass code, bad news — I have no idea, why error is not watched by plumber.

@realph could you remove all plugins below sass , run and post output?

realph commented May 27, 2015

So when I remove all the plugins below gulp-sass , like so:

I still get the same error message, when I deliberately make errors in my CSS. Plumber doesn’t seem to be working.

holic commented May 28, 2015

@realph Try calling gulp-sass with sass.sync instead of sass .

SandHilt commented May 28, 2015

@holic You’re right! @realph keep code but remove return.

gulp.task(‘sass’, function() <
gulp.src(. )
.pipe(plumber())
.pipe(sass(<. >));
>);

realph commented Jun 6, 2015

@SandHilt That seems to have fixed it. Thanks!

silvenon commented Jun 12, 2015

Hm, it’s best to use sync when not returning the stream then, I guess? Otherwise I sometimes get some weird errors because my styles task didn’t finish yet.

d3viant0ne commented Sep 22, 2015

@holic — GG worked like a charm after your suggestion to «rtfm» 🙂

gligoran commented Sep 23, 2015

@SandHilt, @realph : Just be aware that removing return before gulp.src will cause task dependencies to not work as they should. While a dependent task will wait for its dependencies, those dependencies will seem to end before they’re actually done. If you have the return dependent task will actually wait for all the streams to end before running.

Читайте также:  Как настроить бандикам чтобы работал микрофон

d3viant0ne commented Sep 23, 2015

@gligoran — Yeah and that ended up not being an option for me. I managed to get it working with the return statement after a bit of dinking around.

TheAggressive commented Oct 2, 2015

@joshtoo how did you get it to work?

d3viant0ne commented Oct 3, 2015

@TheAggressive — If you can point me to a repo i’ll take a look at your gulp build.

TheAggressive commented Oct 3, 2015

@joshtoo I got it to work this way:

would that do the trick?

d3viant0ne commented Oct 3, 2015

TheAggressive commented Oct 3, 2015

d3viant0ne commented Oct 3, 2015

alextrastero commented Nov 12, 2017

Removing return worked for me

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

Gulp выдаёт ошибку. Как решить?

Прохожу курс по вёрстке от WebForMySelf и в 3 уроке мы собираем проект на Gulp. Делал всё по уроку, только удалил модуль pngquant(он у меня не работает, пишет, что система не подходит).
Вот package.json

Вот сам gulpfile.js (мой)

  • Вопрос задан более двух лет назад
  • 472 просмотра

[15:18:45] Using gulpfile D:\яяяяяяя\Program NeFiles\курс по вёрстке\www\gulpfile.js
[15:18:45] Starting ‘build’.
[15:18:45] ‘build’ errored after 6.08 ms
[15:18:45] TypeError: gulp.hasTask is not a function
at D:\яяяяяяя\Program NeFiles\курс по вёрстке\www\node_modules\run-sequence\index.js:23:22
at Array.forEach ()
at verifyTaskSets (D:\яяяяяяя\Program NeFiles\курс по вёрстке\www\node_modules\run-sequence\index.js:17:11)
at runSequence (D:\яяяяяяя\Program NeFiles\курс по вёрстке\www\node_modules\run-sequence\index.js:130:2)
at D:\яяяяяяя\Program NeFiles\курс по вёрстке\www\gulpfile.js:126:3
at taskWrapper (D:\яяяяяяя\Program NeFiles\курс по вёрстке\www\node_modules\undertaker\lib\set-task.js:13:15)
at bound (domain.js:395:14)
at runBound (domain.js:408:12)
at asyncRunner (D:\яяяяяяя\Program NeFiles\курс по вёрстке\www\node_modules\async-done\index.js:55:18)
at process._tickCallback (internal/process/next_tick.js:61:11)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! fashion@1.0.0 build: `gulp build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the fashion@1.0.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Andrew\AppData\Roaming\npm-cache\_logs\2019-04-06T12_18_45_559Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! fashion@1.0.0 start: `npm run build && gulp serve`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the fashion@1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Andrew\AppData\Roaming\npm-cache\_logs\2019-04-06T12_18_45_644Z-debug.log

D:\яяяяяяя\Program NeFiles\курс по вёрстке\www>gulp -v
«gulp» не является внутренней или внешней
командой, исполняемой программой или пакетным файлом.

D:\яяяяяяя\Program NeFiles\курс по вёрстке\www>npm gulp -v
6.4.1

D:\яяяяяяя\Program NeFiles\курс по вёрстке\www>npm start

> fashion@1.0.0 start D:\яяяяяяя\Program NeFiles\курс по вёрстке\www
> npm run build && gulp serve

> fashion@1.0.0 build D:\яяяяяяя\Program NeFiles\курс по вёрстке\www
> gulp build

Источник

Оцените статью