-
Notifications
You must be signed in to change notification settings - Fork 4
/
gulpfile.js
291 lines (257 loc) · 8.94 KB
/
gulpfile.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
const fs = require('fs');
const gulp = require('gulp');
const $ = require('gulp-load-plugins')();
const del = require('del');
const browserSync = require('browser-sync');
const browserify = require('browserify');
const watchify = require('watchify');
const source = require('vinyl-source-stream');
const buffer = require('vinyl-buffer');
const log = require('fancy-log');
const errorify = require('errorify');
const historyApiFallback = require('connect-history-api-fallback');
const through2 = require('through2');
const { compile: collecticonsCompile } = require('collecticons-processor');
const {
appTitle,
appDescription,
twitterHandle
} = require('./app/assets/scripts/config/production').default;
// /////////////////////////////////////////////////////////////////////////////
// --------------------------- Variables -------------------------------------//
// ---------------------------------------------------------------------------//
const bs = browserSync.create();
const baseurl = process.env.BASEURL || '';
// Environment
// Set the correct environment, which controls what happens in config.js
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
// When being built by circle is set to staging unless we're in the prod branch
if (process.env.CIRCLE_BRANCH) {
if (process.env.CIRCLE_BRANCH === process.env.PRODUCTION_BRANCH) {
process.env.NODE_ENV = 'production';
} else if (process.env.CIRCLE_BRANCH === process.env.STAGING_BRANCH) {
process.env.NODE_ENV = 'staging';
} else {
process.env.NODE_ENV = 'circle';
}
}
// /////////////////////////////////////////////////////////////////////////////
// ------------------------- Helper functions --------------------------------//
// ---------------------------------------------------------------------------//
const isDev = () => process.env.NODE_ENV === 'development';
const readPackage = () => JSON.parse(fs.readFileSync('package.json'));
// Set the version in an env variable so it gets replaced in the config.
process.env.APP_VERSION = readPackage().version;
// /////////////////////////////////////////////////////////////////////////////
// ------------------------- Callable tasks ----------------------------------//
// ---------------------------------------------------------------------------//
function clean () {
return del(['.tmp', 'dist']);
}
function serve () {
bs.init({
port: 9000,
server: {
baseDir: ['.tmp', 'app'],
routes: {
'/node_modules': './node_modules'
},
ghostMode: false,
middleware: [historyApiFallback()]
},
rewriteRules: [
{
// Replace the baseUrl placeholder on runtime.
match: /{{baseurl}}/g,
replace: ''
},
{ match: /{{appTitle}}/g, replace: appTitle },
{ match: /{{appDescription}}/g, replace: appDescription },
{ match: /{{twitterHandle}}/g, replace: twitterHandle }
]
});
// watch for changes
gulp.watch(
[
'app/*.html',
'app/assets/graphics/**/*',
'!app/assets/icons/collecticons/**/*'
],
bs.reload
);
gulp.watch('app/assets/icons/collecticons/**', collecticons);
gulp.watch('package.json', vendorScripts);
}
module.exports.clean = clean;
module.exports.serve = gulp.series(
collecticons,
gulp.parallel(vendorScripts, javascript),
serve
);
module.exports.default = gulp.series(
clean,
collecticons,
gulp.parallel(vendorScripts, javascript),
gulp.parallel(html, imagesImagemin),
finish
);
// /////////////////////////////////////////////////////////////////////////////
// ------------------------- Browserify tasks --------------------------------//
// ------------------- (Not to be called directly) ---------------------------//
// ---------------------------------------------------------------------------//
// Compiles the user's script files to bundle.js.
// When including the file in the index.html we need to refer to bundle.js not
// main.js
function javascript () {
var brs = browserify({
entries: ['./app/assets/scripts/main.js'],
debug: true,
cache: {},
packageCache: {},
bundleExternal: false,
fullPaths: true
})
.on('log', log);
if (isDev()) {
brs
.plugin(watchify)
.plugin(errorify)
.on('update', bundler);
}
function bundler () {
var b = brs.bundle();
if (!isDev()) {
b.on('error', function (e) {
throw new Error(e);
});
}
b = b
.pipe(source('bundle.js'))
.pipe(buffer());
if (isDev()) {
// Source maps.
b = b
.pipe($.sourcemaps.init({ loadMaps: true }))
.pipe($.sourcemaps.write('./'));
}
return b
.pipe(gulp.dest('.tmp/assets/scripts'))
.pipe(bs.stream());
}
return bundler();
}
// Vendor scripts. Basically all the dependencies in the package.js.
// Therefore be careful and keep the dependencies clean.
function vendorScripts () {
// Ensure package is updated.
const pkg = readPackage();
// Note on how this works:
// To have smaller bundles and speed up compilations, the dependencies are
// kept in a vendor bundle. Browserify allows us to exclude all external
// dependencies, and then require them all in another bundle. To require
// them we basically use everything that's under `dependencies` in the
// package.json. However when we access files in the module folder directly
// (like something inside a folder - my-module/folder/file), browserify can't
// find them in the dependencies list. (in this example the dependency would
// only be my-module). In these cases they have to be explicitly added.
const extra = [
// Any file directly accessed on a module folder:
// my-module/folder/file
];
var vb = browserify({
debug: true,
require: pkg.dependencies ? Object.keys(pkg.dependencies).concat(extra) : []
})
.bundle()
.on('error', log.bind(log, 'Browserify Error'))
.pipe(source('vendor.js'))
.pipe(buffer());
if (isDev()) {
// Source maps.
vb = vb
.pipe($.sourcemaps.init({ loadMaps: true }))
.pipe($.sourcemaps.write('./'));
}
return vb
.pipe(gulp.dest('.tmp/assets/scripts/'))
.pipe(bs.stream());
}
// /////////////////////////////////////////////////////////////////////////////
// ------------------------- Collecticon tasks -------------------------------//
// --------------------- (Font generation related) ---------------------------//
// ---------------------------------------------------------------------------//
function collecticons () {
return collecticonsCompile({
dirPath: 'app/assets/icons/collecticons/',
fontName: 'Collecticons',
authorName: 'Development Seed',
authorUrl: 'https://developmentseed.org/',
catalogDest: 'app/assets/scripts/styles/collecticons/',
preview: false,
experimentalFontOnCatalog: true,
experimentalDisableStyles: true
});
}
// //////////////////////////////////////////////////////////////////////////////
// --------------------------- Helper tasks -----------------------------------//
// ----------------------------------------------------------------------------//
function finish () {
return gulp.src('dist/**/*').pipe($.size({ title: 'build', gzip: true }));
}
// After being rendered by jekyll process the html files. (merge css files, etc)
function html () {
return gulp
.src('app/*.html')
.pipe($.useref({ searchPath: ['.tmp', 'app', '.'] }))
.pipe(cacheUseref())
.pipe($.if('*.js', $.terser()))
.pipe($.if('*.css', $.csso()))
.pipe($.if(/\.(css|js)$/, $.rev()))
// Add a prefix to all replacements so next line catches them.
.pipe($.revRewrite({ prefix: '{{baseurl}}' }))
.pipe($.replace('{{baseurl}}', baseurl))
.pipe($.replace('{{appTitle}}', appTitle))
.pipe($.replace('{{appDescription}}', appDescription))
.pipe($.replace('{{twitterHandle}}', twitterHandle))
.pipe(gulp.dest('dist'));
}
function imagesImagemin () {
return gulp
.src(['app/assets/graphics/**/*'])
.pipe(
$.imagemin([
$.imagemin.gifsicle({ interlaced: true }),
$.imagemin.mozjpeg({ quality: 80, progressive: true }),
$.imagemin.optipng({ optimizationLevel: 5 }),
// don't remove IDs from SVGs, they are often used
// as hooks for embedding and styling.
$.imagemin.svgo({ plugins: [{ cleanupIDs: false }] })
])
)
.pipe(gulp.dest('dist/assets/graphics'));
}
/**
* Caches the useref files.
* Avoid sending repeated js and css files through the minification pipeline.
* This happens when there are multiple html pages to process.
*/
function cacheUseref () {
/* eslint-disable-next-line prefer-const */
let files = {
// path: content
};
return through2.obj(function (file, enc, cb) {
const path = file.relative;
if (files[path]) {
// There's a file in cache. Check if it's the same.
const prev = files[path];
if (Buffer.compare(file.contents, prev) !== 0) {
this.push(file);
}
} else {
files[path] = file.contents;
this.push(file);
}
cb();
});
}