-
Notifications
You must be signed in to change notification settings - Fork 12
/
gulpfile.js
386 lines (342 loc) · 10.8 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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
/* eslint-disable no-console */
const autoprefixer = require('autoprefixer');
const fs = require('fs');
const gulp = require('gulp');
const babel = require('gulp-babel');
const cleanCSS = require('gulp-clean-css');
const concat = require('gulp-concat');
const gulpCount = require('gulp-count');
const gulpErrorHandler = require('gulp-error-handle');
const header = require('gulp-header');
const gulpif = require('gulp-if');
const plumber = require('gulp-plumber');
const postcss = require('gulp-postcss');
const cssvariables = require('postcss-css-variables');
const merge = require('merge-stream');
const rename = require('gulp-rename');
const rimraf = require('gulp-rimraf');
const sass = require('gulp-sass')(require('sass'));
const sourcemaps = require('gulp-sourcemaps');
const uglify = require('gulp-uglify');
const path = require('path');
const named = require('vinyl-named');
const webpack = require('webpack');
const webpackStream = require('webpack-stream');
const nodemon = require('gulp-nodemon');
const browserSync = require('browser-sync');
const change = require('gulp-change');
const { rewriteStaticAssetPaths } = require('./middleware/assets');
const webpackConfig = require('./webpack.config');
const browserlist = ['> 0.2%', 'last 10 version', 'not dead'];
const baseScripts = [
'./node_modules/jquery/dist/jquery.min.js',
'./node_modules/form-serializer/dist/jquery.serialize-object.min.js',
'./static/scripts/tether/tether.min.js',
'./static/scripts/bootstrap/bootstrap.min.js',
'./static/scripts/chosen/chosen.jquery.min.js',
'./static/scripts/base.js',
'./static/scripts/toggle/bootstrap-toggle.min.js',
'./static/scripts/qrcode/kjua-0.1.1.min.js',
'./static/scripts/ajaxconfig.js',
];
// specify css files (e.g. in node modules) that should be copied to the build directory
const baseStyles = [
{ dirname: 'calendar/', filename: 'fullcalendar.min.css', src: './node_modules/@fullcalendar/core/main.min.css' },
{ dirname: 'calendar/', filename: 'daygrid.min.css', src: './node_modules/@fullcalendar/daygrid/main.min.css' },
{ dirname: 'calendar/', filename: 'timegrid.min.css', src: './node_modules/@fullcalendar/timegrid/main.min.css' },
];
function themeName() {
return process.env.SC_THEME || 'default';
}
const EXIT_ON_ERROR = process.env.GULP_EXIT_ON_ERROR
? process.env.GULP_EXIT_ON_ERROR === 'true'
: process.env.NODE_ENV !== 'development';
const nonBaseScripts = [
'./static/scripts/**/*.js',
].concat(baseScripts.map((script) => `!${script}`));
// used by almost all gulp tasks instead of gulp.src(...)
// plumber prevents pipes from stopping when errors occur
// changed only passes on files that were modified since last time
function withTheme(src) {
if (typeof src === 'string') {
return [src, `./theme/${themeName()}/${src.slice(2)}`];
}
return src.concat(src
.map((e) => `./theme/${themeName()}/${e.slice(2)}`));
}
const handleError = (error) => {
console.error(error);
process.exit(1);
};
const beginPipe = (src) => gulp
.src(withTheme(src), { allowEmpty: true, since: gulp.lastRun('build-all') })
.pipe(gulpif(EXIT_ON_ERROR, gulpErrorHandler(handleError), plumber()))
const beginPipeAll = (src) => gulp
.src(withTheme(src), { allowEmpty: true, since: gulp.lastRun('build-all') })
.pipe(gulpif(EXIT_ON_ERROR, gulpErrorHandler(handleError), plumber()))
// copy images
// uses gulp.src instead of beginPipe for performance reasons (logging is slow)
gulp.task('images', () => gulp
.src(withTheme('./static/images/**/*.*'))
.pipe(gulp.dest(`./build/${themeName()}/images`)));
// minify static/other
// uses gulp.src instead of beginPipe for performance reasons (logging is slow)
gulp.task('other', () => gulp
.src(withTheme('./static/other/**/*.*'))
.pipe(gulp.dest(`./build/${themeName()}/other`)));
// minify static/other
// uses gulp.src instead of beginPipe for performance reasons (logging is slow)
gulp.task('other-with-theme', gulp.series('other', () => gulp
.src(withTheme('./static/other/**/*.*'))
.pipe(gulp.dest(`./build/${themeName()}/other`))));
let firstRun = true;
gulp.task('styles', () => {
const themeFile = `./theme/${themeName()}/style.scss`;
return beginPipe('./static/styles/**/*.{css,sass,scss}')
.pipe(header(fs.readFileSync(themeFile, 'utf8')))
.pipe(sourcemaps.init())
.pipe(sass({
sourceMap: true,
includePaths: ['node_modules'],
}).on('error', handleError))
.pipe(postcss([
cssvariables({
preserve: true,
}),
autoprefixer({
browsers: browserlist,
}),
]))
.pipe(cleanCSS({
compatibility: 'ie9',
}))
.pipe(change(rewriteStaticAssetPaths))
.pipe(sourcemaps.write('./sourcemaps'))
.pipe(gulp.dest(`./build/${themeName()}/styles`))
.pipe(browserSync.stream());
});
const copyStyle = (dirname, filename, src) => gulp.src(src)
.pipe(rename((targetPath) => {
targetPath.basename = path.parse(filename).name;
targetPath.dirname = dirname;
}))
.pipe(gulp.dest(`./build/${themeName()}/styles`));
gulp.task('copy-styles',
() => merge(baseStyles.map(({ dirname, filename, src }) => copyStyle(dirname, filename, src))));
gulp.task('styles-done', gulp.series('styles'), () => {
firstRun = false;
});
// copy fonts
gulp.task('fonts', () => beginPipe('./static/fonts/**/*.{eot,svg,ttf,woff,woff2}')
.pipe(gulp.dest(`./build/${themeName()}/fonts`)));
// copy static assets
gulp.task('static', () => beginPipe('./static/*')
.pipe(gulp.dest(`./build/${themeName()}/`)));
// compile/transpile JSX and ES6 to ES5 and minify scripts
gulp.task('scripts', () => beginPipeAll(nonBaseScripts)
.pipe(
named((file) => {
// As a preparation for webpack stream: Transform nonBaseScripts paths
// e.g. '/static/scripts/schics/schicEdit.blub.min.js' -> 'schics/schicEdit.blub.min'
const initialPath = file.history[0].split('scripts')[1];
const pathSegments = initialPath.split('.');
const concretePath = pathSegments
.slice(0, pathSegments.length - 1)
.join('.');
const fileName = concretePath
.split('')
.slice(1)
.join('');
return fileName;
}),
)
.pipe(webpackStream(webpackConfig, webpack))
.pipe(gulp.dest(`./build/${themeName()}/scripts`))
.pipe(browserSync.stream()));
// compile/transpile JSX and ES6 to ES5, minify and concatenate base scripts into all.js
gulp.task('base-scripts', () => beginPipeAll(baseScripts)
.pipe(gulpCount('## js-files selected'))
.pipe(babel({
presets: [
[
'@babel/preset-env',
{
modules: false,
targets: browserlist.join(', '),
},
],
],
}))
.pipe(uglify())
.pipe(concat('all.js'))
.pipe(gulp.dest(`./build/${themeName()}/scripts`)));
// compile vendor SASS/SCSS to CSS and minify it
gulp.task('vendor-styles', () => beginPipe('./static/vendor/**/*.{sass,scss}')
.pipe(sourcemaps.init())
.pipe(sass({
sourceMap: true,
}))
.pipe(postcss([
autoprefixer({
browsers: browserlist,
}),
]))
.pipe(cleanCSS({
compatibility: 'ie9',
}))
.pipe(sourcemaps.write('./sourcemaps'))
.pipe(gulp.dest(`./build/${themeName()}/vendor`))
.pipe(browserSync.stream()));
// compile/transpile vendor JSX and ES6 to ES5 and minify scripts
gulp.task('vendor-scripts', () => beginPipe('./static/vendor/**/*.js')
.pipe(babel({
compact: false,
presets: [
[
'@babel/preset-env',
{
modules: false,
targets: browserlist.join(', '),
},
],
],
plugins: ['@babel/plugin-transform-react-jsx'],
}))
.pipe(uglify())
.pipe(gulp.dest(`./build/${themeName()}/vendor`)));
// copy other vendor files
gulp.task('vendor-assets', () => beginPipe([
'./static/vendor/**/*.*',
'!./static/vendor/**/*.js',
'!./static/vendor/**/*.{sass,scss}',
]).pipe(gulp.dest(`./build/${themeName()}/vendor`)));
// copy node modules
const nodeModules = {
// example
// 'module/path/to/keep': [
// '**/*', // matched files, e.g. copy all files in folder
// 'folder/**/*', // folders defined by name will be flattened
// ],
// mathjax
mathjax: ['MathJax.js'],
'mathjax/config': ['**/*'],
'mathjax/extensions': ['**/*'],
'mathjax/fonts': ['**/*'],
'mathjax/jax': ['**/*'],
'mathjax/localization': ['**/*'],
// font-awesome
'font-awesome/fonts': [
'**/*',
],
// material design
'@mdi/font': [
'**/*',
],
// video.js
'video.js/dist': ['video.min.js'],
'video.js/dist/lang': ['*.js'],
};
gulp.task('node-modules', () => {
const promises = [];
for (const [module, modulePaths] of Object.entries(nodeModules)) {
promises.push(
gulp.src(modulePaths.map((modulePath) => `./node_modules/${module}/${modulePath}`))
.pipe(gulp.dest(`./build/${themeName()}/vendor-optimized/${module}`)),
);
}
return Promise.all(promises);
});
// clear build folder + smart cache
gulp.task('clear', () => gulp
.src(
[
'./build/*',
'./.gulp-changed-smart.json',
'./.webpack-changed-plugin-cache/*',
],
{
read: false,
allowEmpty: true,
},
)
.pipe(rimraf()));
// clear gulp cache without removing current build
gulp.task('clear-cache', () => gulp
.src(
[
'./.gulp-changed-smart.json',
'./.webpack-changed-plugin-cache/*',
],
{
read: false,
allowEmpty: true,
},
)
.pipe(rimraf({})));
// run all tasks, processing changed files
gulp.task('build-all', gulp.series(
'images',
'other',
'fonts',
'other-with-theme',
'node-modules',
'styles',
'styles-done',
'copy-styles',
'scripts',
'base-scripts',
'vendor-styles',
'vendor-scripts',
'vendor-assets',
'static',
));
gulp.task('build-theme-files', gulp.series('styles', 'styles-done', 'images', 'static'));
// watch and run corresponding task on change, process changed files only
gulp.task('watch', gulp.series('build-all', () => {
const watchOptions = { interval: 1000 };
gulp.watch(baseScripts, watchOptions, gulp.series('base-scripts'));
gulp.watch(
withTheme('./static/styles/**/*.{css,sass,scss}'),
watchOptions,
gulp.series('styles', 'styles-done'),
);
gulp.watch(withTheme('./static/images/**/*.*'), watchOptions, gulp.series('images'))
.on('change', browserSync.reload);
gulp.watch(withTheme(nonBaseScripts), watchOptions, gulp.series('scripts'));
gulp.watch(withTheme('./static/vendor/**/*.*'), watchOptions, gulp.series('vendor-styles',
'vendor-scripts',
'vendor-assets'));
gulp.watch(withTheme('./static/*.*'), watchOptions, gulp.series('static'));
}));
gulp.task('nodemon', (cb) => {
let started = false;
return nodemon({
ext: 'js hbs json',
script: './bin/www',
watch: ['views/', 'controllers/', 'helpers'],
exec: 'node --inspect=9310',
}).on('start', () => {
if (!started) {
cb();
started = true;
}
setTimeout(browserSync.reload, 3000); // server-start takes some time
});
});
gulp.task('browser-sync', () => {
browserSync.init(null, {
proxy: 'http://localhost:3100',
open: false,
port: 7000,
ghostMode: false,
reloadOnRestart: false,
socket: {
clients: {
heartbeatTimeout: 60000,
},
},
});
});
gulp.task('watch-reload', gulp.parallel('watch', 'nodemon', 'browser-sync'));
// run this if only 'gulp' is run on the commandline with no task specified
gulp.task('default', gulp.series('build-all'));