This repository has been archived by the owner on Feb 17, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gulpfile.babel.js
executable file
·341 lines (278 loc) · 9.96 KB
/
gulpfile.babel.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
/* eslint-disable no-loop-func */
import 'dotenv/config';
import browserify from 'browserify';
import browserSync from 'browser-sync';
import del from 'del';
import fetch from 'node-fetch';
import fs from 'fs';
import gulp from 'gulp';
import Handlebars from 'handlebars';
import igdeploy from 'igdeploy';
import mkdirp from 'mkdirp';
import mergeStream from 'merge-stream';
import path from 'path';
import runSequence from 'run-sequence';
import source from 'vinyl-source-stream';
import subdir from 'subdir';
import vinylBuffer from 'vinyl-buffer';
import watchify from 'watchify';
const $ = require('auto-plug')('gulp');
const AUTOPREFIXER_BROWSERS = [
'ie >= 8',
'ff >= 30',
'chrome >= 34',
];
const DEPLOY_TARGET = ''; // e.g. 'features/YOUR-PROJECT-NAME'
const BROWSERIFY_ENTRIES = [
'scripts/main.js',
];
const BROWSERIFY_TRANSFORMS = [
'babelify',
'debowerify',
];
const OTHER_SCRIPTS = [
'scripts/top.js'
];
let env = 'development';
// function to get an array of objects that handle browserifying
function getBundlers(useWatchify) {
return BROWSERIFY_ENTRIES.map(entry => {
var bundler = {
b: browserify(path.posix.resolve('client', entry), {
cache: {},
packageCache: {},
fullPaths: useWatchify,
debug: useWatchify
}),
execute: function () {
var stream = this.b.bundle()
.on('error', $.util.log.bind($.util, 'Browserify error'))
.pipe(source(entry.replace(/\.js$/, '.bundle.js')));
// skip sourcemap creation if we're in 'serve' mode
if (useWatchify) {
stream = stream
.pipe(vinylBuffer())
.pipe($.sourcemaps.init({loadMaps: true}))
.pipe($.sourcemaps.write('./'));
}
return stream.pipe(gulp.dest('.tmp'));
}
};
// register all the transforms
BROWSERIFY_TRANSFORMS.forEach(function (transform) {
bundler.b.transform(transform);
});
// upgrade to watchify if we're in 'serve' mode
if (useWatchify) {
bundler.b = watchify(bundler.b);
bundler.b.on('update', function (files) {
// re-run the bundler then reload the browser
bundler.execute().on('end', browserSync.reload);
// also report any linting errors in the changed file(s)
gulp.src(files.filter(file => subdir(path.resolve('client'), file))) // skip bower/npm modules
.pipe($.eslint())
.pipe($.eslint.format());
});
}
return bundler;
});
}
// compresses images (client => dist)
gulp.task('compress-images', () => gulp.src('client/**/*.{jpg,png,gif,svg}')
.pipe($.imagemin({
progressive: true,
interlaced: true,
}))
.pipe(gulp.dest('dist'))
);
// minifies JS (.tmp => dist)
gulp.task('minify-js', () => gulp.src('.tmp/**/*.js')
.pipe($.uglify({output: {inline_script: true}})) // eslint-disable-line camelcase
.pipe(gulp.dest('dist'))
);
// minifies CSS (.tmp => dist)
gulp.task('minify-css', () => gulp.src('.tmp/**/*.css')
.pipe($.minifyCss({compatibility: '*'}))
.pipe(gulp.dest('dist'))
);
// copies over miscellaneous files (client => dist)
gulp.task('copy-misc-files', () => gulp.src(
[
'client/**/*',
'!client/**/*.{html,scss,js,jpg,png,gif,svg,hbs}', // all handled by other tasks,
], {dot: true})
.pipe(gulp.dest('dist'))
);
// inlines short scripts/styles and minifies HTML (dist => dist)
gulp.task('finalise-html', done => {
gulp.src('.tmp/**/*.html')
.pipe(gulp.dest('dist'))
.on('end', () => {
gulp.src('dist/**/*.html')
.pipe($.smoosher())
.pipe($.minifyHtml())
.pipe(gulp.dest('dist'))
.on('end', done);
});
});
// clears out the dist and .tmp folders
gulp.task('clean', del.bind(null, ['.tmp/*', 'dist/*', '!dist/.git'], {dot: true}));
// // runs a development server (serving up .tmp and client)
gulp.task('serve', ['download-data', 'styles'], function (done) {
var bundlers = getBundlers(true);
// execute all the bundlers once, up front
var initialBundles = mergeStream(bundlers.map(function (bundler) {
return bundler.execute();
}));
initialBundles.resume(); // (otherwise never emits 'end')
initialBundles.on('end', function () {
// use browsersync to serve up the development app
browserSync({
notify: false,
server: {
baseDir: ['.tmp', 'client'],
routes: {
'/bower_components': 'bower_components'
}
}
});
// refresh browser after other changes
gulp.watch(['client/styles/**/*.{scss,css}'], ['styles', 'scsslint', browserSync.reload]);
gulp.watch(['client/images/**/*'], browserSync.reload);
gulp.watch(['./client/**/*.hbs', 'client/words.json'], () => {
runSequence('templates', browserSync.reload);
});
runSequence('templates', done);
});
});
// builds and serves up the 'dist' directory
gulp.task('serve:dist', ['build'], done => {
require('browser-sync').create().init({
open: false,
notify: false,
server: 'dist',
}, done);
});
// preprocess/copy scripts (client => .tmp)
// (this is part of prod build task; not used during serve)
gulp.task('scripts', () => mergeStream([
// bundle browserify entries
getBundlers().map(bundler => bundler.execute()),
// also copy over 'other' scripts
gulp.src(OTHER_SCRIPTS.map(script => 'client{/_hack,}/' + script)).pipe(gulp.dest('.tmp'))
]));
// builds stylesheets with sass/autoprefixer
gulp.task('styles', () => gulp.src('client/**/*.scss')
.pipe($.sourcemaps.init())
.pipe($.sass({includePaths: 'bower_components'}).on('error', $.sass.logError))
.pipe($.autoprefixer({browsers: AUTOPREFIXER_BROWSERS}))
.pipe($.sourcemaps.write('./'))
.pipe(gulp.dest('.tmp'))
);
// lints JS files
gulp.task('eslint', () => gulp.src('client/scripts/**/*.js')
.pipe($.eslint())
.pipe($.eslint.format())
.pipe($.if(env === 'production', $.eslint.failAfterError()))
);
// lints SCSS files
gulp.task('scsslint', () => gulp.src('client/styles/**/*.scss')
.pipe($.scssLint({bundleExec: true}))
.pipe($.if(env === 'production', $.scssLint.failReporter()))
);
// makes a production build (client => dist)
gulp.task('build', done => {
env = 'production';
runSequence(
// preparatory
['clean', /* 'scsslint', 'eslint', */ 'download-data'],
// preprocessing (client/templates => .tmp)
['scripts', 'styles', 'templates'],
// optimisation (+ copying over misc files) (.tmp/client => dist)
['minify-js', 'minify-css', 'compress-images', 'copy-misc-files'],
// finalise the HTML in dist (by inlining small scripts/stylesheets then minifying the HTML)
['finalise-html'],
done);
});
// task to deploy to the interactive server
gulp.task('deploy', done => {
if (!DEPLOY_TARGET) {
console.error('Please specify a DEPLOY_TARGET in your gulpfile!');
process.exit(1);
}
igdeploy({
src: 'dist',
destPrefix: '/var/opt/customer/apps/interactive.ftdata.co.uk/var/www/html',
dest: DEPLOY_TARGET,
}, error => {
if (error) return done(error);
console.log(`Deployed to http://ig.ft.com/${DEPLOY_TARGET}/`);
});
});
// downloads the data from bertha to client/words.json
const SPREADSHEET_URL = `https://bertha.ig.ft.com/republish/publish/gss/${process.env.SPREADSHEET_KEY}/data`;
gulp.task('download-data', () => fetch(SPREADSHEET_URL)
.then(res => res.json())
.then(spreadsheet => {
const words = {};
for (const row of spreadsheet) {
if (words[row.slug]) throw new Error('Already exists: ' + row.slug);
words[row.slug] = row;
}
let wordArray = Object.keys(words);
let slugIndex = wordArray.sort();
for (const row of spreadsheet) {
let currentSlug = row.slug;
words[currentSlug].relatedwords = words[currentSlug].relatedwords.map(relatedWordSlug => ({
slug: relatedWordSlug,
word: words[relatedWordSlug].word
}));
let slugPointer = null;
if (slugIndex.indexOf(currentSlug) > 0) {
slugPointer = slugIndex.indexOf(currentSlug) - 1;
} else {
slugPointer = slugIndex.length - 1;
}
words[currentSlug].previousWord = {
slug: words[slugIndex[slugPointer]].slug,
word: words[slugIndex[slugPointer]].word
};
if (slugIndex.indexOf(currentSlug) < slugIndex.length - 1) {
slugPointer = slugIndex.indexOf(currentSlug) + 1;
} else {
slugPointer = 0;
}
words[currentSlug].nextWord = {
slug: words[slugIndex[slugPointer]].slug,
word: words[slugIndex[slugPointer]].word
};
words[currentSlug].showPerpetratorData = words[currentSlug].perpetrator
|| words[currentSlug].usagesource ? true : null;
}
fs.writeFileSync('client/words.json', JSON.stringify(words, null, 2));
let dateIndex = wordArray.sort(function (a, b) {
return new Date(words[b].submissiondate) - new Date(words[a].submissiondate);
});
const homewords = {};
homewords[dateIndex[0]] = words[dateIndex[0]];
let randomNumber = Math.floor(Math.random() * (dateIndex.length - 1)) + 1;
homewords[dateIndex[randomNumber]] = words[dateIndex[randomNumber]];
fs.writeFileSync('client/homewords.json', JSON.stringify(homewords, null, 2));
})
);
gulp.task('templates', () => {
Handlebars.registerPartial('top', fs.readFileSync('client/top.hbs', 'utf8'));
Handlebars.registerPartial('bottom', fs.readFileSync('client/bottom.hbs', 'utf8'));
const definitionPageTemplate = Handlebars.compile(fs.readFileSync('client/definition-page.hbs', 'utf8'));
const words = JSON.parse(fs.readFileSync('client/words.json', 'utf8'));
for (const slug of Object.keys(words)) {
const word = words[slug];
const html = definitionPageTemplate(word);
mkdirp.sync(`.tmp/${slug}`);
fs.writeFileSync(`.tmp/${slug}/index.html`, html);
}
const homewords = JSON.parse(fs.readFileSync('client/homewords.json', 'utf8'));
const mainPageTemplate = Handlebars.compile(fs.readFileSync('client/main-page.hbs', 'utf8'));
const html = mainPageTemplate({homewords});
fs.writeFileSync(`.tmp/index.html`, html);
});