This repository has been archived by the owner on Jul 25, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgulpfile.js
480 lines (409 loc) · 14.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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
'use strict';
const fs = require('fs');
// -----------------------------------------------------------------------------
// Configuration
// -----------------------------------------------------------------------------
const SassInput = './components/vf-componenet-rollup/index.scss';
const SassOutput = './public/css';
const autoprefixerOptions = { browsers: ['last 2 versions', '> 5%', 'Firefox ESR'] };
const config = JSON.parse(fs.readFileSync('./package.json'));
global.vfName = config.vfConfig.vfName;
global.vfNamespace = config.vfConfig.vfNamespace;
global.vfComponentPath = __dirname + '/components';
global.vfThemePath = './tools/vf-frctl-theme';
// -----------------------------------------------------------------------------
// Dependencies
// -----------------------------------------------------------------------------
const gulp = require('gulp');
const path = require('path');
const notify = require('gulp-notify');
const shell = require('gulp-shell');
const rename = require('gulp-rename');
const watch = require('gulp-watch');
const ListStream = require('list-stream');
// Sass and CSS Stuff
const sass = require('gulp-sass');
const autoprefixer = require('gulp-autoprefixer');
const cssnano = require('gulp-cssnano');
const sourcemaps = require('gulp-sourcemaps');
const nodeModuleImport = require('@node-sass/node-module-importer');
const recursive = require('./tools/css-generator/recursive-readdir');
// Linting things
const postcss = require('gulp-postcss');
const reporter = require('postcss-reporter');
const syntax_scss = require('postcss-scss');
const gulpStylelint = require('gulp-stylelint');
// Image things
const svgmin = require('gulp-svgmin');
// JS Stuff
const concat = require('gulp-concat');
const uglify = require('gulp-uglify');
// const sourcemaps = require('gulp-sourcemaps');
const babel = require('gulp-babel');
const rollup = require('gulp-better-rollup');
const includePaths = require('rollup-plugin-includepaths');
const componentPath = path.resolve(__dirname, 'components' );
// Local Server Stuff
const browserSync = require('browser-sync').create();
const reload = browserSync.reload;
// Design Tokens
const theoG = require('gulp-theo')
const theo = require('theo')
// -----------------------------------------------------------------------------
// Sass and CSS Tasks
// -----------------------------------------------------------------------------
gulp.task('css', function() {
const sassOpts = {
// Import sass files
// We'll check to see if the file exists before passing
// it to sass for compilation
importer: [nodeModuleImport, function(url,prev,done) {
var truncatedUrl = url.split(/[/]+/).pop();
var parentFile = prev.split(/[/]+/).pop();
// If you do not want to interveen in certain file names
// if (parentFile == '_index.scss' || parentFile == '_vf-mixins.scss' || parentFile == 'vf-functions.scss') {
// return null;
// }
// only intervene in index.scss rollups
if (parentFile == 'index.scss') {
if (availableComponents[url]) {
done(url);
} else if (availableComponents['_'+truncatedUrl]) {
// maybe it was an _filename.scss?
done(url);
} else if (availableComponents[truncatedUrl]) {
done(url);
} else {
let importWarning = `Couldn\'t find ${url} referenced in ${prev}`;
console.warn(importWarning);
done({ contents: `/* ${importWarning} */` });
}
} else {
return null;
}
}],
includePaths: [
path.resolve(__dirname, 'components/vf-sass-config/variables'),
path.resolve(__dirname, 'components/vf-sass-config/functions'),
path.resolve(__dirname, 'components/vf-sass-config/mixins'),
path.resolve(__dirname, 'components'),
path.resolve(__dirname, 'components/vf-form'),
path.resolve(__dirname, 'components/vf-core-components'),
path.resolve(__dirname, 'node_modules'),
]
};
// Find all the component sass files available.
// We'll pass this as a variable to our sass build so we can
// only include the file if it exists.
var availableComponents = {}; // track the components avaialble
return gulp
.src(['components/**/**/*.scss'], {
allowEmpty: true,
ignore: ['components/**/index.scss']
})
.pipe(ListStream.obj(function (err, data) {
if (err)
throw err
data.forEach(function (value, i) {
// Keep only the file name
var value = value.history[0].split(/[/]+/).pop();
availableComponents[value] = true;
});
runSassBuild();
}));
function runSassBuild(){
gulp
.src(SassInput)
.pipe(sourcemaps.init())
.pipe(sass(sassOpts))
.on(
'error',
notify.onError(function(error) {
process.emit('exit') // this fails precommit, but allows guld dev to work
return 'Problem at file: ' + error.message;
})
)
.pipe(autoprefixer(autoprefixerOptions))
.pipe(browserSync.stream())
.pipe(sourcemaps.write())
.pipe(rename(
{
basename: "styles"
}
))
.pipe(gulp.dest(SassOutput))
.pipe(cssnano())
.pipe(rename(
{
suffix: ".min"
}
))
.pipe(gulp.dest(SassOutput));
}
});
// Sass Lint
gulp.task("scss-lint", function lintCssTask() {
// For stylelint config rules see .stylelinrc
return gulp
.src(
['components/**/embl-*.scss', 'components/**/vf-*.scss', '!components/**/index.scss', '!assets/**/*.scss']
)
.pipe(gulpStylelint({
failAfterError: true,
reporters: [
{formatter: "string", console: true}
]
}));
});
// -----------------------------------------------------------------------------
// Scripts Tasks
// -----------------------------------------------------------------------------
// Rollup all JS imports into CJS and babel them to ES5
gulp.task('scripts:es5', function() {
let includePathOptions = {
include: {},
paths: [
path.resolve(__dirname, 'components'),
path.resolve(__dirname, 'components/vf-core-components'),
path.resolve(__dirname, 'components/vf-form'),
],
external: ['vfTabs'],
extensions: ['.js']
};
return gulp.src('./components/vf-componenet-rollup/scripts.js')
// .pipe(sourcemaps.init())
.pipe(rollup({
// There is no `input` option as rollup integrates into the gulp pipeline
treeshake: false,
// external: ['vfTabs','vfBanner'],
plugins: [
babel({
"presets": [
[
"@babel/preset-env",
{
"targets": "> 0.25%, not dead, last 2 versions"
}
]
]
}),
includePaths(includePathOptions)
]
}, {
// Rollups `sourcemap` option is unsupported. Use `gulp-sourcemaps` plugin instead
format: 'cjs',
}))
// inlining the sourcemap into the exported .js file
// .pipe(sourcemaps.write())
.pipe(gulp.dest('./public/scripts'));
});
// Eventually we'll want to support ES6 natively with ES5 as fallback, `scripts.es5.js`
gulp.task('scripts:modern', function() {
return gulp.src('./components/vf-componenet-rollup/scripts.js')
.pipe(rename(function (path) {
path.extname = ".modern.js";
}))
.pipe(gulp.dest('./public/scripts'));
});
// -----------------------------------------------------------------------------
// Component Assets
// -----------------------------------------------------------------------------
gulp.task('component-assets', function() {
return gulp
.src(['./components/**/assets/**/*','./components/vf-core-components/**/assets/**/*'])
.pipe(gulp.dest('./public/assets'));
});
// -----------------------------------------------------------------------------
// Component Assets
// -----------------------------------------------------------------------------
gulp.task('svg', () => {
return gulp
.src('./components/**/*.svg')
.pipe(svgmin())
.pipe(gulp.dest('./components'));
});
// -----------------------------------------------------------------------------
// Design Token Tasks
// -----------------------------------------------------------------------------
const theoGeneratedFileWarning = `// This file has been dynamically generated from design tokens
// Please do NOT edit directly.`;
const theoSourceTokenLocation = `// Source: {{relative "${ componentPath }" meta.file}}`;
const theoGeneratedPropertiesTemplate = `${theoGeneratedFileWarning}
${theoSourceTokenLocation}
:root {
{{#each props as |prop|}}
{{#if prop.comment}}
{{{trimLeft (indent (comment (trim prop.comment)))}}}
{{/if}}
--{{kebabcase prop.name}}: {{#eq prop.type "string"}}"{{/eq}}{{{prop.value}}}{{#eq prop.type "string"}}"{{/eq}};
{{/each}}
}
`;
const theoGeneratedMapTemplate = `${theoGeneratedFileWarning}
${theoSourceTokenLocation}
\${{stem meta.file}}-map: (
{{#each props as |prop|}}
{{#if prop.comment}}
{{{trimLeft (indent (comment (trim prop.comment)))}}}
{{/if}}
'{{kebabcase prop.name}}': ({{#eq prop.type "string"}}"{{/eq}}{{{prop.value}}}{{#eq prop.type "string"}}"{{/eq}}),
{{/each}}
);
`;
const theoGeneratedSassTemplate = `${theoGeneratedFileWarning}
${theoSourceTokenLocation}
{{#each props as |prop|}}
{{#if prop.comment}}
{{{trimLeft (indent (comment (trim prop.comment)))}}}
{{/if}}
\${{kebabcase prop.name}}: {{#eq prop.type "string"}}"{{/eq}}{{{prop.value}}}{{#eq prop.type "string"}}"{{/eq}};
{{/each}}
`;
// Register design tokens to be processed by Theo
gulp.task('tokens:typographic-scale', () =>
gulp.src('./components/vf-design-tokens/typographic-scales/*.yml')
.pipe(theoG({
transform: { type: 'web' },
format: { type: 'typography-map' }
}))
.pipe(rename(function (path) {
path.extname = ".scss";
}))
.pipe(gulp.dest('./components/vf-sass-config/variables'))
);
gulp.task('tokens:variables', () =>
gulp.src('./components/vf-design-tokens/variables/*.yml')
.pipe(theoG({
transform: { type: 'web' },
format: { type: 'variables.scss' }
}))
.pipe(gulp.dest('./components/vf-sass-config/variables'))
);
gulp.task('tokens:maps', () =>
gulp.src(['./components/vf-design-tokens/maps/*.yml', '!./components/vf-design-tokens/typographic-scales/*.yml'])
.pipe(theoG({
transform: { type: 'web' },
format: { type: 'map.scss' }
}))
.pipe(gulp.dest('./components/vf-sass-config/variables'))
);
gulp.task('tokens:props', () =>
gulp.src(['./components/vf-design-tokens/maps/*.yml'])
.pipe(theoG({
transform: { type: 'web' },
format: { type: 'custom-properties.scss' }
}))
.pipe(gulp.dest('./components/vf-sass-config/variables'))
);
// Register output format for token types
theo.registerFormat( "variables.scss",`${theoGeneratedSassTemplate}`);
theo.registerFormat( "map.scss",`${theoGeneratedMapTemplate}`);
theo.registerFormat( "custom-properties.scss",`${theoGeneratedPropertiesTemplate}`);
// The Theo typography token processor is a bit more complex
// and uses a custom format as a function
theo.registerFormat("typography-map", result => {
let { category, type } = result
.get("props")
.first()
.toJS();
return `${theoGeneratedFileWarning}
// Source: ${path.basename(result.getIn(["meta", "file"]))}
$vf-${category}--${type}: (
${result
.get("props")
.map(
prop => `
'${prop.get("name")}': (
'font-size': ${prop.getIn(["value", "font-size"])},
'font-weight': ${prop.getIn(["value", "font-weight"])},
'line-height': ${prop.getIn(["value", "line-height"])}
),`
)
.sort()
.join("\n")}
);
`;
});
// -----------------------------------------------------------------------------
// Fractal Tasks
// -----------------------------------------------------------------------------
gulp.task('frctlStart', function(done) {
const fractal = require('./fractal.js').initialize('server',fractalReadyCallback);
function fractalReadyCallback() {
done();
}
});
gulp.task('frctlBuild', function(done) {
const fractal = require('./fractal.js').initialize('build',fractalReadyCallback);
function fractalReadyCallback() {
// Copy compiled css/js and other assets
gulp.src('./public/**/*')
.pipe(gulp.dest('./build'));
console.info('Copied `/public` assets.');
done();
}
});
// -----------------------------------------------------------------------------
// CSS Generator Tasks
// -----------------------------------------------------------------------------
var genCss = function (option) {
var file_name = path.basename(path.dirname(option.file_path)) + ".css";
return gulp.src(option.file_path)
.pipe(sass({
includePaths: [
path.resolve(__dirname, 'components/vf-sass-config/variables'),
path.resolve(__dirname, 'components/vf-sass-config/functions'),
path.resolve(__dirname, 'components/vf-sass-config/mixins'),
path.resolve(__dirname, 'components'),
path.resolve(__dirname, 'components/vf-form'),
path.resolve(__dirname, 'components/vf-core-components'),
path.resolve(__dirname, 'node_modules')
],
outputStyle: 'expanded'
})
.on('error', sass.logError))
.pipe(autoprefixer(autoprefixerOptions))
.pipe(rename(file_name))
.pipe(gulp.dest(option.dir));
};
gulp.task('CSSGen', function(done) {
recursive(componentPath, ['*.css'], function (err, files) {
files.forEach(function(file) {
if (file.file.indexOf('index.scss') > -1) {
genCss(file);
}
});
});
done();
});
// -----------------------------------------------------------------------------
// Watch Tasks
// -----------------------------------------------------------------------------
gulp.task('watch', function(done) {
gulp.watch('./components/**/*.scss', gulp.series(['css', 'scss-lint'])).on('change', reload);
gulp.watch('./components/**/*.js', gulp.series('scripts')).on('change', reload);
gulp.watch('./components/**/**/assets/*.svg', gulp.series('svg','component-assets')).on('change', reload);
gulp.watch(['./components/**/**/assets/*', '!./components/**/**/assets/*.svg'], gulp.series('component-assets')).on('change', reload);
});
// -----------------------------------------------------------------------------
// Default Tasks
// -----------------------------------------------------------------------------
gulp.task('scripts', gulp.series(
'scripts:es5', 'scripts:modern'
));
gulp.task('dev', gulp.series(
'component-assets', ['css', 'scripts'], 'frctlStart', 'watch'
));
gulp.task('tokens', gulp.parallel(
'tokens:variables', 'tokens:typographic-scale', 'tokens:maps', 'tokens:props'
));
// Build as a static site for CI
gulp.task('build', gulp.series(
'tokens', 'scss-lint', 'CSSGen', 'css', 'component-assets', 'scripts', 'frctlBuild'
));
gulp.task('prepush-test', gulp.parallel(
'scss-lint', 'css'
));
gulp.task('component', shell.task(
['yo ./tools/component-generator']
));