-
Notifications
You must be signed in to change notification settings - Fork 0
/
gulpfile.js
344 lines (292 loc) · 8.58 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
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
342
343
344
/* eslint comma-dangle: 0 */
/* eslint-disable */
"use strict";
// General
const argv = require("yargs").argv;
const browserSync = require("browser-sync");
const del = require("del");
const fs = require("fs");
const ghPages = require('gulp-gh-pages');
const gulp = require("gulp");
const gulpif = require("gulp-if");
const gutil = require("gulp-util");
const historyApiFallback = require('connect-history-api-fallback');
const sourcemaps = require("gulp-sourcemaps");
const watch = require("gulp-watch");
// SASS
const autoprefixer = require("gulp-autoprefixer");
const filter = require("gulp-filter");
const sass = require("gulp-sass");
// PUG
const pug = require("gulp-pug");
// JS
const babelify = require("babelify"); // eslint-disable-line no-unused-vars
const browserify = require("browserify");
const buffer = require("vinyl-buffer");
const rename = require("gulp-rename");
const source = require("vinyl-source-stream");
const stripDebug = require("gulp-strip-debug");
const uglify = require("gulp-uglify");
const watchify = require("watchify");
/* eslint-enable */
/* eslint-disable no-unused-vars */
// Constants
const SOURCE_PATH = "./src";
const BUILD_PATH = "./build";
const STATIC_FILES = ["/html/**", "/img/*.png", "/img/*.jpg", "/img/*.svg", "/img/*.ico", "*.html", "/js/jquery-3.1.1.min.js", "/favicon.ico", "CNAME", "sitemap.xml"]; // relative to /src/
const SCRIPTS_TO_WATCH = [`${SOURCE_PATH}/js/script.js`];
const KEEP_FILES = true;
const OPEN_TAB = argv.open || argv.o;
// Do not change this one!
const STATIC_FILES_TO_WATCH = [];
/* eslint-enable no-unused-vars */
/**
* Simple way to check for development/production mode.
*/
function isProduction() {
return argv.production || argv.p;
}
/**
* Logs the current build mode on the console.
*/
function logBuildMode() {
if ( isProduction() ) {
gutil.log( gutil.colors.green( "Running production build..." ) );
} else {
gutil.log( gutil.colors.red( "Running development build..." ) );
}
}
/**
* Handles errors
*/
function logError( err ) {
if ( err.plugin === "gulp-sass" ) {
gutil.log( `${gutil.colors.yellow( "SASS error" )}: ${gutil.colors.red( err.messageOriginal.slice( 0, -1 ) )} in ${gutil.colors.cyan( err.relativePath )} on line ${err.line}, column ${err.column}` );
} else if ( err.fileName ) {
gutil.log( `${gutil.colors.yellow( err.name )}: ${gutil.colors.red( err.fileName.replace( `${__dirname}/src/js/`, "" ) )}: Line ${gutil.colors.magenta( err.lineNumber )} & Column ${gutil.colors.magenta( err.columnNumber || err.column )}: ${gutil.colors.blue( err.description )}` );
} else {
// Browserify error..
gutil.log( `${gutil.colors.yellow( err.name )}: ${gutil.colors.red( err.message )}` );
}
}
/**
* Copies folders from folders specified in STATIC_FOLDERS.
*/
function copyStatic() {
STATIC_FILES.forEach( ( v ) => {
let path;
let output;
if ( fs.existsSync( `${SOURCE_PATH}${v}` ) && fs.lstatSync( `${SOURCE_PATH}${v}` ).isDirectory() ) {
path = `${SOURCE_PATH}${v}`;
output = `${BUILD_PATH}${v}`;
path += "/*.*";
} else {
let file = v;
if ( v[0] !== "/" ) {
file = `/${file}`;
}
path = `${SOURCE_PATH}${file}`;
output = `${BUILD_PATH}${file}`;
output = output.split( "/" );
output.pop();
output = output.join( "/" );
}
gulp.src( path )
.pipe( gulp.dest( output ) );
} );
}
/**
* Deletes all content inside the './build' folder.
* If 'keepFiles' is true, no files will be deleted. This is a dirty workaround since we can't have
* optional task dependencies :(
* Note: keepFiles is set to true by gulp.watch (see serve()) and reseted here to avoid conflicts.
*/
function cleanBuild() {
if ( !KEEP_FILES ) {
del( ["build/**/*.*"] );
// del(["build/**/"]);
}
copyStatic();
}
/**
* Converts time to appropriate unit.
*/
function showDuration( t ) {
if ( t >= 1000 ) {
return `${t / 1000} s`;
}
if ( t <= 1 ) {
return `${t * 1000} μs`;
}
return `${t} ms`;
}
/**
* Transforms ES2015 code into ES5 code.
* Creates sourcemaps if production.
* Uglifies if not in production.
*/
function buildScript( toWatch, path ) {
const filename = path.split( "/" ).pop();
let bundler = browserify( path, {
basedir: __dirname,
debug: true,
cache: {},
packageCache: {},
fullPaths: toWatch,
plugin: [watchify],
} );
if ( toWatch ) {
bundler = watchify( bundler );
}
bundler.transform( "babelify", { presets: ["es2015"] } );
const rebundle = function() {
const timer = Date.now();
const stream = bundler.bundle().on( "end", () => {
gutil.log( `Started '${gutil.colors.cyan( "scripts" )}' ('${gutil.colors.cyan( filename )}')...` );
} );
return stream
.on( "error", logError )
.pipe( source( filename ) )
.pipe( buffer() )
.pipe( sourcemaps.init( { loadMaps: true } ) )
.pipe( gulpif( isProduction(), stripDebug() ) )
.pipe( gulpif( isProduction(), uglify() ) )
.pipe( gulpif( !isProduction(), sourcemaps.write( "./" ) ) )
.pipe( gulp.dest( `${BUILD_PATH}/js` ) )
.on( "end", () => {
const taskName = `'${gutil.colors.cyan( "scripts" )}' ('${gutil.colors.cyan( filename )}')`;
const taskTime = gutil.colors.magenta( showDuration( Date.now() - timer ) );
gutil.log( `Finished ${taskName} after ${taskTime}` );
} )
.pipe( browserSync.stream() );
};
bundler.on( "update", rebundle );
return rebundle();
}
/**
* Generates SASS.
*/
function buildSass() {
const options = {
sourcemap: true,
style: "expanded",
};
if ( isProduction() ) {
options.style = "compressed";
}
return gulp.src( `${SOURCE_PATH}/sass/**/*.sass` )
.pipe( sourcemaps.init() )
.pipe( sass( options ).on( "error", logError ) )
.pipe( autoprefixer( "last 1 version", "> 1%", "ie 8", "ie 7" ) )
.pipe( gulpif( !isProduction(), sourcemaps.write( "./" ) ) )
.pipe( gulp.dest( `${BUILD_PATH}/css` ) )
.pipe( filter( ["**/*.css"] ) )
.pipe( browserSync.stream() );
}
/**
* Generates pug.
*/
function buildPug() {
gulp.src( `${SOURCE_PATH}/*.pug` )
.pipe(
pug( {
"pretty": isProduction(),
} )
)
.pipe( gulp.dest( BUILD_PATH ) )
.pipe(
browserSync.stream()
);
return gulp.src( `${SOURCE_PATH}/en/*.pug` )
.pipe(
pug( {
"pretty": isProduction(),
} )
)
.pipe( gulp.dest( `${BUILD_PATH}/en` ) )
.pipe(
browserSync.stream()
);
}
/**
* Adds paths to array conatining files that will be watched.
*/
function watchStatic() {
STATIC_FILES.forEach( ( v ) => {
let path;
if ( fs.existsSync( `${SOURCE_PATH}${v}` ) && fs.lstatSync( `${SOURCE_PATH}${v}` ).isDirectory() ) {
path = `${SOURCE_PATH}${v}`;
path += "/*.*";
} else {
let file = v;
if ( v[0] !== "/" ) {
file = `/${file}`;
}
path = `${SOURCE_PATH}${file}`;
}
STATIC_FILES_TO_WATCH.push( path );
} );
}
/**
* Starts the Browsersync server.
* Watches for file changes in the 'src' folder.
*/
function serve() {
const options = {
serveStatic: [
{
route: "/browser-sync-client-transition",
dir: "./node_modules/browser-sync-client-transition"
},
{
route: "/build",
dir: "./build"
}
],
open: OPEN_TAB,
};
let server = argv.proxy || false;
if ( server ) {
if ( typeof server === "boolean" ) {
server = "localhost";
}
options.proxy = { "target": server };
} else {
options.server = BUILD_PATH;
}
browserSync( options );
}
gulp.task( "cleanBuild", cleanBuild );
gulp.task( "copyStatic", copyStatic );
gulp.task( "sass", buildSass );
gulp.task( "pug", buildPug );
gulp.task( "watchScripts", () => {
SCRIPTS_TO_WATCH.forEach( ( v ) => {
buildScript( true, v );
} );
} );
gulp.task( "watchStatic", () => {
watchStatic();
} );
gulp.task( "watch", ["copyStatic", "sass", "pug", "watchStatic", "watchScripts"], () => {
watch( `${SOURCE_PATH}/sass/**/*.sass`, () => {
gulp.start( "sass" );
} );
watch( [`${SOURCE_PATH}/*.pug`, `${SOURCE_PATH}/en/*.pug`, `${SOURCE_PATH}/includes/**/*.pug`], () => {
gulp.start( "pug" );
} );
watch( STATIC_FILES_TO_WATCH, () => {
copyStatic();
browserSync.reload();
} );
} );
gulp.task( "serve", ["cleanBuild", "watch"], serve );
gulp.task( "default", ["serve"], logBuildMode );
gulp.task( "deploy", () => {
const msg = argv.message || argv.m || null;
const options = { branch: "master", force: true };
if ( msg !== null ) {
options.message = msg;
}
return gulp.src( "./build/**/*" ).pipe( ghPages( options ) );
} );