Web_Designer_UK__May_2018
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
Developer tutorials<br />
Automate your workflow with Gulp<br />
fromasingletemplate.Inthiscase,onepageforeachcar<br />
make,whichdisplaysalistofavailablemodels.Createa<br />
newtaskcalled‘models-list’andgrabthesamecardata<br />
file,deletingcachefromanypreviousbuildslikebefore.<br />
gulp.task(‘models-list’, function() {<br />
console.log(‘Generating car pages ’);<br />
delete require.cache[require.<br />
resolve(`./${dataDev}/cars.json`)];<br />
let config = require(`./${dataDev}/cars.<br />
json`);<br />
});<br />
20. Rendernewpages–part2<br />
We’llnowloopthroughthemakesfromthecardata<br />
usingamapfunction.Bydefault,therearethreedifferent<br />
makesinthecardata,sotheloopshouldrunthreetimes.<br />
Foreachone,we’llfirstpassthetemplatetoNunjucksand<br />
injectthecardata,thenrenameittoincludethemakein<br />
itsfilenamebeforefinallysendingthecompiledHTMLto<br />
the ‘htmlDist’ directory.<br />
config[‘makes’].map(function(make) {<br />
return gulp.src(`${htmlDev}/template.<br />
html`)<br />
.pipe(nunjucks.compile({<br />
date: config[‘date’],<br />
make: make.name,<br />
cars: make.cars<br />
}))<br />
.pipe(rename({basename:<br />
`${make.name.toLowerCase()}-leaseprices`}))<br />
.pipe(gulp.dest(htmlDist));<br />
});<br />
21. Automating XML sitemaps<br />
Next, we’ll use Gulp to generate an XML sitemap based<br />
on our statically generated HTML pages. Typically, we<br />
would need one for SEO purposes, and having to update<br />
it every time a page is added would be a pain. Install<br />
‘gulp-sitemap’ and include it as a dependency called<br />
‘sitemap’ in gulpfile.<br />
22. Create sitemap task – part 1<br />
Create a new task called ‘sitemap’ and within it, use ‘src()’<br />
to grab any compiled HTML files from the ‘htmlDist’<br />
directory. To save a bit of processing time, we’ll set the<br />
method’s ‘read’ option to false, meaning it won’t read<br />
each files contents, instead only registering its existence.<br />
gulp.task(‘sitemap’, function() {<br />
console.log(‘Generating sitemap ’);<br />
return gulp.src(`${htmlDist}/*.html`, {<br />
read: false<br />
})<br />
});<br />
23. Create sitemap task – part 2<br />
We need to pass the compiled HTML files to the sitemap<br />
plugin so they can be registered. The options we’re<br />
configuring here largely correspond to tags within an<br />
XML sitemap page entry. One thing to note is that in<br />
places, we’re using regex through the ‘replace()’ method.<br />
This removes the ‘.html’ file extension where visible, as<br />
typically,onalivewebserver,thesewouldn’tbeusedin<br />
web addresses.<br />
.pipe(sitemap({<br />
siteUrl: ‘http://www.example.com’,<br />
mappings: [{<br />
pages: [ ‘**/*.html’ ],<br />
changefreq: ‘monthly’,<br />
lastmod: Date.now(),<br />
hreflang: [{<br />
lang: ‘en-GB’,<br />
getHref(siteUrl, file, lang, loc) {<br />
return siteUrl + file.<br />
replace(/\.\w+$/, ‘’);<br />
}<br />
}],<br />
getLoc(siteUrl, loc, entry) {<br />
return loc.replace(/\.\w+$/, ‘’);<br />
}<br />
}]<br />
}))<br />
.pipe(gulp.dest(htmlDist));<br />
24. Copy static files<br />
Inanybuildsystem,sometimestheonlythingweneed<br />
to do with certain files is copy them from directory A to<br />
directoryB.Inthisproject,there’sacollectionoffonts<br />
whereweneedtodojustthat.Createanewtaskcalled<br />
‘copy’,callthe‘src()’methodandgrabanythingin‘fonts’<br />
within the ‘dev’ directory, before using the ‘dest()’<br />
method to copy them to ‘dist’.<br />
gulp.task(‘copy-fonts’, function() {<br />
console.log(‘Copying fonts ’);<br />
return gulp.src(`${dev}/fonts/**`)<br />
.pipe(gulp.dest(`${dist}/fonts`));<br />
});<br />
25. Createawebserver<br />
Beingabletoeasilycreateasimplewebservertoserve<br />
ourprojectfromwouldbeabigconvenience.Thisis<br />
something we can do in Gulp with the ‘gulp-webserver<br />
plugin’,whichweshouldinstallandthenlistasa<br />
dependency called ‘webserver’ in gulpfile.<br />
Under the Production Tasks header, add the task below.<br />
We’llsettheplugin’s‘livereload’optiontotrue,sothat<br />
when changes are made, the page automatically<br />
refreshes in the browser.<br />
gulp.task(‘serve’, function() {<br />
console.log(“Serving the project ”);<br />
gulp.src(`${dist}`).pipe(webserver({<br />
livereload: true<br />
}));<br />
});<br />
26. Install run-sequence<br />
Nowwehaveallofourtasksinplace,itwouldbeuseful<br />
ifwecouldrunthemallwithoneeasycommand,rather<br />
thanbeingforcedtorunthemindividually.<br />
Themostreadablewayforustodothisrequiresa<br />
plugin called ‘run-sequence’. Install it in the usual<br />
mannerandincludeitasaprojectdependencycalled<br />
‘runSequence’.Next,createanewtaskunderthe<br />
ProductionTasksheadercalled‘build’.<br />
gulp.task(‘build’, function() {<br />
});<br />
27. Creating the build task<br />
With run-sequence, we can define whether tasks should<br />
run synchronously or asynchronously, which is helpful<br />
when one task (Such as UnCSS) depends on another<br />
being completed first (such as SASS).<br />
Gulp comes with this kind of functionality out of the<br />
box in the form of task dependencies, but run-sequence<br />
enables us to define this behaviour in a much more<br />
obvious, readable way, in large tasks. Add the snippet<br />
below to the build task. Tasks passed on their own run<br />
synchronously, while tasks passed in an array all run<br />
asynchronously.<br />
runSequence(<br />
‘deleteDist’,<br />
[‘makes-list’, ‘models-list’,<br />
‘sass’, ‘js’, ‘copy-fonts’, ‘images’],<br />
[‘uncss’, ‘sitemap’]<br />
);<br />
28. Dev task – part 1<br />
So far, we have created a build task which does exactly<br />
that, build the task. One issue with this is that during<br />
development, we’ll keep having to run this or individual<br />
tasksaswemakechangestoourfiles,aswellasserve<br />
our project. Let’s create another task called ‘dev’ that<br />
automates all of this.<br />
You may notice that before the task’s function, we’re<br />
adding an array mentioning the ‘build’ and ‘serve’ tasks,<br />
which tells Gulp to run these first. These are the same<br />
tasks dependencies mentioned in Step 27, and are more<br />
suited to this simple use.<br />
gulp.task(‘dev’, [‘build’, ‘serve’],<br />
function() {<br />
});<br />
29. Dev task – part 2<br />
Next, we’ll use a method belonging to Gulp called<br />
‘watch()’. This keeps an eye on any files we pass to it via<br />
the first parameter, and if they change, runs the task<br />
passed in the second. This removes the need for us to<br />
manually run tasks as we develop the project. Add these<br />
watch tasks to ‘dev’ and that should cover everything.<br />
gulp.watch([`${htmlDev}/**/*.html`,<br />
`${dev}/data/cars.json`],<br />
[‘makes-list’, ‘models-list’]);<br />
gulp.watch(`${imgDev}/*.+(png|jpg|jpeg|gif)`<br />
,[‘images’]);<br />
gulp.watch(`${sassDev}/**/*.scss`,[‘sass’]);<br />
gulp.watch(`${jsDev}/**/*.js`,[‘js’]);<br />
30. Run dev task<br />
Finally, run the dev task in terminal with ‘gulp dev’ and<br />
watch as the project is built and a server is created at<br />
localhost:8000. From then on, if we change any of the<br />
files which are being watched, the appropriate task will<br />
then run and recompile your edited file.<br />
Congratulations! You now have a build system<br />
powered by Gulp.js.<br />
84 _________________________________________________tutorial