Gulp is a great tool for front end automation tasks. In this article I will show you how I use Gulp to boost my front end development efficiency.
Gulp Plugins
We will use lots of Gulp plugins in our tasks. With gulp-load-plugins we don’t need to import them mannually.
Config
Define a config variable for all our settings so we can reuse them throughout the file and it makes the code more friendly. We use gulp-util to set our environment. Append –production to ./node_modules/.bin/gulp command to tell him, “We are now on production. Don’t generate source maps. Don’t instantiate local server. Thanks!”
Sass
This task takes all scss files, parse/bundle/minify/revision, and generate source map. When we use “inspect” in browser, brower will show us the original scss file instead of minified css thanks to source map. And we use gulp-if to prevent generating source map on production.
React
This task uses babel and browserify to transform all JSX files, bundle/uglify/revision, and generate source map as well. We have to use vinyl-buffer to change a stream to a buffer.
HTML
Js and Css file paths are always changing due to revision. We update html file to use the new paths with the help of gulp-compile-handlebars.
Watch
This task watches all src file changes and automatically run related tasks. Notice that all above tasks have plugins.connect.reload() in the pipe to refresh the browser for us. We can open up browswer, code editor, terminal side by side. Whenever we make a change in the editor, terminal will show us the result of each task, browser will auto refresh and reflect the changes. This is like a magic. We use run-sequence to make sure gulp runs html task after js task is finished so that we can get the correct revision file path.
Connect
gulp-connect will create an instance of local web server for development and support live reload.
Open
gulp-open opens up development browser for us.
Default
Finally we set default tasks for Gulp. We run ./node_modules/.bin/gulp for development and ./node_modules/.bin/gulp --production for production.