⬆️ ⬇️

Gulp: how I collected a project for production, ran livereload and made error catching

image




I want to share the story of my acquaintance with gulp and how I solved some problems during development. The material is focused on those who are familiar with nodejs and are just beginning to get acquainted with gulp , as well as those who are looking for a solution to a similar problem. As the name suggests, the article consists of three chapters.



At the beginning



My acquaintance with gulp began two months ago, when, being unemployed for a while, I began to think about getting settled into the office. Having monitored the vacancies, I decided to retrain from php developer to frontend - benefit from the experience and knowledge allowed to do this quickly. And now, after some time, not without effort, I was taken for a trial period. I vaguely imagine how I managed to do this, but when I came to work on the first day, I wrote the notepad page on both sides with terms that I heard for the first time ... On that day, I realized that I was lost in the century of web developers.



Introduction



I will tell about my three problems in the process of exploring gulp:

  1. How to build compressed (production) and uncompressed versions of the project without much effort?
  2. How to force the browser to automatically restart the project when making changes?
  3. How to intercept errors in the code so that the watch task will not crash if the code has made an error?


For clarity, I made a small project. You can see the link . Download with all the variations of gulpfile.js from the current article, you can archive the link .

')

Project structure:

gulpfile.habrahabr.webulla.ru/ - assets/ - - core/ - - - components/ - - - - woman.js - - - application.js - web/ - - assets/ - - index.html - gulpfile.js - package.json 


A working gulpfile.js , which I will complement with the solutions analyzed in the article (in the archive - gulpfile-0-original.js ):

 'use strict'; //   gulp var gulp = require('gulp'); var browserify = require('gulp-browserify'); //     var rootDir = '.'; var sourceDir = rootDir + '/assets'; //     var destDir = rootDir + '/web/assets'; //      //     //       //     scripts   var components = { scripts: { source: sourceDir + '/core/application.js', dest: destDir, watch: sourceDir + '/core/**/*.js', options: { paths: ['./node_modules', sourceDir], debug: false, fullPaths: true } } }; //     gulp.task('scripts', function () { gulp.src(components.scripts.source) .pipe(browserify(components.scripts.options)) .pipe(gulp.dest(components.scripts.dest)); }); //        gulp.task('watch:scripts', ['scripts'], function () { //    ,     gulp.watch(components.scripts.watch, ['scripts']); }); gulp.task('default', ['scripts']); gulp.task('watch', ['watch:scripts']); 


Building a project from the console:

 gulp 


Running a task to track changes in files:

 gulp watch 


Chapter 1 - Build compressed (production) and uncompressed project versions



Problem



To reduce the size of the compiled application.js I use the gulp-uglify package . The problem is that it is more convenient for me to search for jambs and debug the code in uncompressed code (without using gulp-uglify ). In general, how to make so that without edits in gulpfile.js you can collect both an uncompressed version of the project for debugging and a compressed version for production?



Decision



I do not remember where I peeped this decision, but I liked it and want to share it with you. It consists in passing a certain flag when running gulp from the console:

 #  uncompressed  gulp #  compressed  gulp --production 


For this implementation, I used:



First, put all the necessary packages:

 npm install --save-dev yargs gulp-uglify gulp-if 


Connected packages in gulpfile.js :

 var argv = require('yargs').argv; var gulpif = require('gulp-if'); var uglify = require('gulp-uglify'); 


Added pipe to the scripts task:

 gulp.src(components.scripts.source) .pipe(browserify(components.scripts.options)) .pipe(gulpif(argv.production, uglify())) // <-     .pipe(gulp.dest(components.scripts.dest)); 


Adding this line is equivalent to the following code:

 var src = gulp.src(components.scripts.source) .pipe(browserify(components.scripts.options)); // ,    production if(argv.production) { src.pipe(uglify()); } src.pipe(gulp.dest(components.scripts.dest)); 


Explanation: in the case when argv.production == true , uglify will be applied.



Now I build the uncompressed version of the project with the command:

 gulp 


A build compressed version:

 gulp --production 


The if (argv.production) {...} condition I use in other places, for example, when building styles for production.



Result



Augmented by the solution from this chapter gulpfile.js is in the archive and is called gulpfile-1-production.js .



Chapter 2 - Automatic reloading of the tab with the project in the browser after the changes



Problem



Each time, after making changes to the files and when gulp watch is running, the project is re-assembled, but the page with the project does not reload. I need to switch to chrome and update the project tab. It is convenient to do so when edits are made to the files, and on another screen the browser window with the project automatically reboots with the new code.



Decision



I solved this problem with the gulp-livereload package and the livereload extension for chrome. This extension is available for other browsers: http://livereload.com/ .



Installed the necessary package:

 npm install --save-dev gulp-livereload 


Connected package:

 var livereload = require('gulp-livereload'); 


Added a command to start the server in the watch: scripts task:

  //   livereload.listen(); 


Added server reboot command to scripts task:

 gulp.src(components.scripts.source) .pipe(browserify(components.scripts.options)) .pipe(gulpif(argv.production, uglify())) .pipe(gulp.dest(components.scripts.dest)) .pipe(livereload()); // <-     


Launched gulp watch :

 gulp watch 


Install the chrome livereload extension . For example, the web folder of my project is available at gulpfile.habrahabr.ru.local . I open it in the browser, click on the Enable LiveReload button in the bar and it's done! Each time you save any files monitored by the watch task, the browser page automatically reloads.



Result



Archived gulpfile.js - gulpfile-2-livereload.js .



Chapter 3 - Interception of mistakes made in the project during development



Problem



If I made a mistake in the project scripts, then the working gulp watch task stopped with an error during compilation. I wanted this to happen and gulp watch continued to work.



Decision



For myself, I decided the problem so: I created a separate function for intercepting errors with logging to the console.

 /** *  . * @param e */ var error = function (e) { console.error('Error in plugin "' + e.plugin + '"'); console.error(' "' + e.message + '"'); console.error(' In file "' + e.fileName + '", line "' + e.lineNumber + '".'); console.log('--------------------------------------'); console.log(e); }; 


Added event handling to the gulp scripts task:

  gulp.src(components.scripts.source) .pipe(browserify(components.scripts.options).on('error', error)) // <-  .on('error', error)    .pipe(gulpif(argv.production, uglify())) .pipe(gulp.dest(components.scripts.dest)) .pipe(livereload()); 


Now, even if I make a mistake in the code, I see a notification in the console and I do not need to restart gulp watch.



Result



Updated by gulpfile.js in the archive - gulpfile-3-error.js .



Conclusion



In this article I did not want to retell the documentation or tell something innovative, but shared my experience with gulp and important conclusions for myself. All documentation is available at the links specified in the article.



I would also like to hear the opinion of experienced and knowledgeable people both on the technical side and on the text: whether the material is understandable, maybe it’s worth saying something differently or something else. I would like to learn how to convey my thoughts to people :) Thank you for your attention!



See an example .

Download the sample archive .



Additions to the article



Update as of November 6, 2015 at 12:22

There is gulp-plumber for error handling.
agatische

Source: https://habr.com/ru/post/269673/



All Articles