-
Notifications
You must be signed in to change notification settings - Fork 2
/
gulpfile.js
616 lines (523 loc) · 20.3 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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
const _ = require('lodash');
const del = require('del');
const gulp = require('gulp');
const gulpUtil = require('gulp-util');
const helpers = require('./config/helpers');
/** TSLint checker */
const tslint = require('tslint');
const gulpTslint = require('gulp-tslint');
/** External command runner */
const process = require('process');
const execSync = require('child_process').execSync;
/** File Access */
const fs = require('fs');
const path = require('path');
const gulpFile = require('gulp-file');
/** To properly handle pipes on error */
const pump = require('pump');
/** To upload code coverage to coveralls */
const gulpCoveralls = require('gulp-coveralls');
/** To order tasks */
const runSequence = require('run-sequence');
/** To compile & bundle the library with Angular & Rollup */
const ngc = require('@angular/compiler-cli/src/main').main;
const rollup = require('rollup');
const rollupUglify = require('rollup-plugin-uglify');
const rollupSourcemaps = require('rollup-plugin-sourcemaps');
/** To load templates and styles in Angular components */
const gulpInlineNgTemplate = require('gulp-inline-ng2-template');
/** Sass style */
const sass = require('node-sass');
const cssnano = require('cssnano');
const postcss = require('postcss');
const autoprefixer = require('autoprefixer');
const stripInlineComments = require('postcss-strip-inline-comments');
//Bumping, Releasing tools
const gulpGit = require('gulp-git');
const gulpBump = require('gulp-bump');
const gulpConventionalChangelog = require('gulp-conventional-changelog');
const conventionalGithubReleaser = require('conventional-github-releaser');
/** To load gulp tasks from multiple files */
const gulpHub = require('gulp-hub');
const yargs = require('yargs');
const argv = yargs
.option('version', {
alias: 'v',
describe: 'Enter Version to bump to',
choices: ['patch', 'minor', 'major']
})
.option('ghToken', {
alias: 'gh',
describe: 'Enter Github Token for releasing'
})
.argv;
const config = {
libraryName: 'ngx-lazy-view',
allSrc: 'src/**/*',
allTs: 'src/**/!(*.spec).ts',
allSass: 'src/**/*.(scss|sass)',
allHtml: 'src/**/*.html',
demoDir: 'demo/',
buildDir: 'tmp/',
outputDir: 'dist/',
coverageDir: 'coverage/'
};
const rootFolder = path.join(__dirname);
const buildFolder = path.join(rootFolder, `${config.buildDir}`);
const distFolder = path.join(rootFolder, `${config.outputDir}`);
const es5OutputFolder = path.join(buildFolder, 'lib-es5');
const es2015OutputFolder = path.join(buildFolder, 'lib-es2015');
//Helper functions
const startKarmaServer = (isTddMode, hasCoverage, cb) => {
const karmaServer = require('karma').Server;
const travis = process.env.TRAVIS;
let config = { configFile: `${__dirname}/karma.conf.js`, singleRun: !isTddMode, autoWatch: isTddMode };
if (travis) {
config['browsers'] = ['Chrome_travis_ci']; // 'Chrome_travis_ci' is defined in "customLaunchers" section of config/karma.conf.js
}
config['hasCoverage'] = hasCoverage;
new karmaServer(config, cb).start();
};
const getPackageJsonVersion = () => {
// We parse the json file instead of using require because require caches
// multiple calls so the version number won't be updated
return JSON.parse(fs.readFileSync('./package.json', 'utf8')).version;
};
const isOK = condition => {
return condition ? gulpUtil.colors.green('[OK]') : gulpUtil.colors.red('[KO]');
};
const readyToRelease = () => {
let isTravisPassing = /build #\d+ passed/.test(execSync('npm run check-travis').toString().trim()) ;
let onMasterBranch = execSync('git symbolic-ref --short -q HEAD').toString().trim() === 'master';
let canBump = !!argv.version;
let canGhRelease = argv.ghToken || process.env.CONVENTIONAL_GITHUB_RELEASER_TOKEN;
let canNpmPublish = !!execSync('npm whoami').toString().trim() && execSync('npm config get registry').toString().trim() === 'https://registry.npmjs.org/';
gulpUtil.log(`[travis-ci] Travis build on 'master' branch is passing............................................${isOK(isTravisPassing)}`);
gulpUtil.log(`[git-branch] User is currently on 'master' branch..................................................${isOK(onMasterBranch)}`);
gulpUtil.log(`[npm-publish] User is currently logged in to NPM Registry...........................................${isOK(canNpmPublish)}`);
gulpUtil.log(`[bump-version] Option '--version' provided, with value : 'major', 'minor' or 'patch'.................${isOK(canBump)}`);
gulpUtil.log(`[github-release] Option '--ghToken' provided or 'CONVENTIONAL_GITHUB_RELEASER_TOKEN' variable set......${isOK(canGhRelease)}`);
return isTravisPassing && onMasterBranch && canBump && canGhRelease && canNpmPublish;
};
const execCmd = (name, args, opts, ...subFolders) => {
const cmd = helpers.root(subFolders, helpers.binPath(`${name}`));
return helpers.execp(`${cmd} ${args}`, opts)
.then(exitCode => exitCode === 0 ? Promise.resolve() : Promise.reject())
.catch(e => {
gulpUtil.log(gulpUtil.colors.red(`${name} command failed. See below for errors.\n`));
gulpUtil.log(gulpUtil.colors.red(e));
process.exit(1);
});
};
const execExternalCmd = (name, args, opts) => {
return helpers.execp(`${name} ${args}`, opts)
.then(exitCode => exitCode === 0 ? Promise.resolve() : Promise.reject())
.catch(e => {
gulpUtil.log(gulpUtil.colors.red(`${name} command failed. See below for errors.\n`));
gulpUtil.log(gulpUtil.colors.red(e));
process.exit(1);
});
};
// Compile Sass to css
const styleProcessor = (stylePath, ext, styleFile, callback) => {
/**
* Remove comments, autoprefixer, Minifier
*/
const processors = [
stripInlineComments,
autoprefixer,
cssnano
];
if (/\.(scss|sass)$/.test(ext[0])) {
let sassObj = sass.renderSync({ file: stylePath });
if (sassObj && sassObj['css']) {
let css = sassObj.css.toString('utf8');
postcss(processors).process(css).then(function (result) {
result.warnings().forEach(function (warn) {
gutil.warn(warn.toString());
});
styleFile = result.css;
callback(null, styleFile);
});
}
}
};
/////////////////////////////////////////////////////////////////////////////
// Cleaning Tasks
/////////////////////////////////////////////////////////////////////////////
gulp.task('clean:dist', () => {
return del(config.outputDir);
});
gulp.task('clean:build', () => {
return del(config.buildDir);
});
gulp.task('clean:coverage', () => {
return del(config.coverageDir);
});
gulp.task('clean:doc', ()=>{
return del(`${config.outputDir}/doc`);
});
gulp.task('clean', ['clean:dist', 'clean:coverage', 'clean:build']);
/////////////////////////////////////////////////////////////////////////////
// Compilation Tasks
/////////////////////////////////////////////////////////////////////////////
gulp.task('lint', (cb) => {
pump([
gulp.src(config.allTs),
gulpTslint(
{
program: tslint.Linter.createProgram('./tsconfig.json'),
formatter: 'verbose',
configuration: 'tslint.json'
}),
gulpTslint.report()
], cb);
});
// Inline Styles and Templates into components
gulp.task('inline-templates', (cb) => {
const options = {
base: `${config.buildDir}`,
styleProcessor: styleProcessor,
useRelativePaths: true
};
pump(
[
gulp.src(config.allTs),
gulpInlineNgTemplate(options),
gulp.dest(`${config.buildDir}`)
],
cb);
});
// Prepare files for compilation
gulp.task('pre-compile', (cb)=>{
pump([
gulp.src([config.allSrc]),
gulp.dest(config.buildDir)
], cb);
});
gulp.task('ng-compile',()=>{
return Promise.resolve()
// Compile to ES5.
.then(() => ngc({ project: `${buildFolder}/tsconfig.lib.es5.json` })
.then(exitCode => exitCode === 0 ? Promise.resolve() : Promise.reject())
.then(() => gulpUtil.log('ES5 compilation succeeded.'))
)
// Compile to ES2015.
.then(() => ngc({ project: `${buildFolder}/tsconfig.lib.json` })
.then(exitCode => exitCode === 0 ? Promise.resolve() : Promise.reject())
.then(() => gulpUtil.log('ES2015 compilation succeeded.'))
)
.catch(e => {
gulpUtil.log(gulpUtil.colors.red('ng-compilation failed. See below for errors.\n'));
gulpUtil.log(gulpUtil.colors.red(e));
process.exit(1);
});
});
// Lint, Prepare Build, , Sass to css, Inline templates & Styles and Compile
gulp.task('compile', (cb) => {
runSequence(/*'lint', */'pre-compile', 'inline-templates', 'ng-compile', cb);
});
// Watch changes on (*.ts, *.html, *.sass) and Compile
gulp.task('watch', () => {
gulp.watch([config.allTs, config.allHtml, config.allSass], ['compile']);
});
// Build the 'dist' folder (without publishing it to NPM)
gulp.task('build', ['clean'], (cb) => {
runSequence('compile', 'npm-package', 'rollup-bundle', cb);
});
/////////////////////////////////////////////////////////////////////////////
// Packaging Tasks
/////////////////////////////////////////////////////////////////////////////
// Prepare 'dist' folder for publication to NPM
gulp.task('npm-package', (cb) => {
let pkgJson = JSON.parse(fs.readFileSync('./package.json', 'utf8'));
let targetPkgJson = {};
let fieldsToCopy = ['version', 'description', 'keywords', 'author', 'repository', 'license', 'bugs', 'homepage'];
targetPkgJson['name'] = config.libraryName;
//only copy needed properties from project's package json
fieldsToCopy.forEach((field) => { targetPkgJson[field] = pkgJson[field]; });
targetPkgJson['main'] = `bundles/${config.libraryName}.umd.js`;
targetPkgJson['module'] = `${config.libraryName}.js`;
targetPkgJson['es2015'] = `${config.libraryName}.js`;
targetPkgJson['typings'] = `${config.libraryName}.d.ts`;
// defines project's dependencies as 'peerDependencies' for final users
targetPkgJson.peerDependencies = {};
Object.keys(pkgJson.dependencies).forEach((dependency) => {
targetPkgJson.peerDependencies[dependency] = `^${pkgJson.dependencies[dependency]}`;
});
// copy the needed additional files in the 'dist' folder
pump(
[
gulp.src(['README.md', 'LICENSE', 'CHANGELOG.md',
`${config.buildDir}/lib-es5/**/*.d.ts`,
`${config.buildDir}/lib-es5/**/*.metadata.json`]),
gulpFile('package.json', JSON.stringify(targetPkgJson, null, 2)),
gulp.dest(config.outputDir)
], cb);
});
// Bundles the library as UMD/FESM bundles using RollupJS
gulp.task('rollup-bundle', (cb) => {
return Promise.resolve()
// Bundle lib.
.then(() => {
// Base configuration.
const es5Entry = path.join(es5OutputFolder, `${config.libraryName}.js`);
const es2015Entry = path.join(es2015OutputFolder, `${config.libraryName}.js`);
const globals = {
// Angular dependencies
'@angular/core': 'ng.core',
'@angular/common': 'ng.common',
'@angular/compiler': 'ng.compiler',
'@angular/router': 'ng.router',
'@angular/platform-browser-dynamic': 'ng.platform-browser-dynamic',
'@angular/platform-browser': 'ng.platform-browser',
// Rxjs dependencies
'rxjs/Subject': 'Rx',
'rxjs/add/observable/fromEvent': 'Rx.Observable',
'rxjs/add/observable/forkJoin': 'Rx.Observable',
'rxjs/add/observable/of': 'Rx.Observable',
'rxjs/add/observable/merge': 'Rx.Observable',
'rxjs/add/observable/throw': 'Rx.Observable',
'rxjs/add/operator/auditTime': 'Rx.Observable.prototype',
'rxjs/add/operator/toPromise': 'Rx.Observable.prototype',
'rxjs/add/operator/map': 'Rx.Observable.prototype',
'rxjs/add/operator/filter': 'Rx.Observable.prototype',
'rxjs/add/operator/do': 'Rx.Observable.prototype',
'rxjs/add/operator/share': 'Rx.Observable.prototype',
'rxjs/add/operator/finally': 'Rx.Observable.prototype',
'rxjs/add/operator/catch': 'Rx.Observable.prototype',
'rxjs/add/observable/empty': 'Rx.Observable.prototype',
'rxjs/add/operator/first': 'Rx.Observable.prototype',
'rxjs/add/operator/startWith': 'Rx.Observable.prototype',
'rxjs/add/operator/switchMap': 'Rx.Observable.prototype',
'rxjs/Observable': 'Rx'
// ATTENTION:
// Add any other dependency or peer dependency your library here.
// This is required for UMD bundle users.
};
const rollupBaseConfig = {
moduleName: _.camelCase(config.libraryName),
sourceMap: true,
globals: globals,
external: Object.keys(globals),
plugins: [
rollupSourcemaps()
]
};
// UMD bundle.
const umdConfig = Object.assign({}, rollupBaseConfig, {
entry: es5Entry,
dest: path.join(distFolder, `bundles`, `${config.libraryName}.umd.js`),
format: 'umd',
});
// Minified UMD bundle.
const minifiedUmdConfig = Object.assign({}, rollupBaseConfig, {
entry: es5Entry,
dest: path.join(distFolder, `bundles`, `${config.libraryName}.umd.min.js`),
format: 'umd',
plugins: rollupBaseConfig.plugins.concat([rollupUglify({})])
});
// ESM+ES5 flat module bundle.
const fesm5config = Object.assign({}, rollupBaseConfig, {
entry: es5Entry,
dest: path.join(distFolder, `${config.libraryName}.es5.js`),
format: 'es'
});
// ESM+ES2015 flat module bundle.
const fesm2015config = Object.assign({}, rollupBaseConfig, {
entry: es2015Entry,
dest: path.join(distFolder, `${config.libraryName}.js`),
format: 'es'
});
const allBundles = [
umdConfig,
minifiedUmdConfig,
fesm5config,
fesm2015config
].map(cfg => rollup.rollup(cfg).then(bundle => bundle.write(cfg)));
return Promise.all(allBundles)
.then(() => gulpUtil.log('All bundles generated successfully.'))
})
.catch(e => {
gulpUtil.log(gulpUtil.colors.red('rollup-bundling failed. See below for errors.\n'));
gulpUtil.log(gulpUtil.colors.red(e));
process.exit(1);
});
});
/////////////////////////////////////////////////////////////////////////////
// Documentation Tasks
/////////////////////////////////////////////////////////////////////////////
gulp.task('build:doc', ()=>{
return execCmd('compodoc',`-p tsconfig.json --hideGenerator --disableCoverage -d ${config.demoDir}/dist/doc/`);
});
gulp.task('serve:doc', ['clean:doc'], ()=>{
return execCmd('compodoc',`-p tsconfig.json -s -d ${config.outputDir}/doc/`);
});
/////////////////////////////////////////////////////////////////////////////
// Demo Tasks
/////////////////////////////////////////////////////////////////////////////
const execDemoCmd = (args,opts) => {
if(fs.existsSync(`${config.demoDir}/node_modules`)){
return execCmd('ng', args, opts, `/${config.demoDir}`);
}
else{
gulpUtil.log(gulpUtil.colors.yellow(`No 'node_modules' found in '${config.demoDir}'. Installing dependencies for you..`));
return helpers.installDependencies({ cwd: `${config.demoDir}` })
.then(exitCode => exitCode === 0 ? execCmd('ng', args, opts, `/${config.demoDir}`) : Promise.reject())
.catch(e => {
gulpUtil.log(gulpUtil.colors.red(`ng command failed. See below for errors.\n`));
gulpUtil.log(gulpUtil.colors.red(e));
process.exit(1);
});
}
};
gulp.task('test:demo', ()=>{
return execDemoCmd('test', { cwd: `${config.demoDir}`});
});
gulp.task('serve:demo', ()=>{
return execDemoCmd('serve --proxy-config proxy.conf.json', { cwd: `${config.demoDir}`});
});
gulp.task('build:demo', ()=>{
return execDemoCmd(`build --prod --aot --base-href https://josephliccini.github.io/${config.libraryName}/`, { cwd: `${config.demoDir}`});
});
gulp.task('push:demo', ()=>{
return execCmd('ngh',`--dir ${config.demoDir}/dist --message="chore(demo): :rocket: deploy new version"`);
});
gulp.task('deploy:demo', (cb) => {
runSequence('build:demo', 'build:doc', 'push:demo', cb);
});
/////////////////////////////////////////////////////////////////////////////
// Test Tasks
/////////////////////////////////////////////////////////////////////////////
gulp.task('test', (cb) => {
const ENV = process.env.NODE_ENV = process.env.ENV = 'test';
startKarmaServer(false, true, cb);
});
gulp.task('test:ci', ['clean'], (cb) => {
runSequence('compile', 'test');
});
gulp.task('test:watch', (cb) => {
const ENV = process.env.NODE_ENV = process.env.ENV = 'test';
startKarmaServer(true, true, cb);
});
gulp.task('test:watch-no-cc', (cb) => {//no coverage (useful for debugging failing tests in browser)
const ENV = process.env.NODE_ENV = process.env.ENV = 'test';
startKarmaServer(true, false, cb);
});
/////////////////////////////////////////////////////////////////////////////
// Release Tasks
/////////////////////////////////////////////////////////////////////////////
gulp.task('changelog', (cb) => {
pump(
[
gulp.src('CHANGELOG.md', { buffer: false }),
gulpConventionalChangelog({ preset: 'angular', releaseCount: 0 }),
gulp.dest('./')
], cb);
});
gulp.task('github-release', (cb) => {
if (!argv.ghToken && !process.env.CONVENTIONAL_GITHUB_RELEASER_TOKEN) {
gulpUtil.log(gulpUtil.colors.red(`You must specify a Github Token via '--ghToken' or set environment variable 'CONVENTIONAL_GITHUB_RELEASER_TOKEN' to allow releasing on Github`));
throw new Error(`Missing '--ghToken' argument and environment variable 'CONVENTIONAL_GITHUB_RELEASER_TOKEN' not set`);
}
conventionalGithubReleaser(
{
type: 'oauth',
token: argv.ghToken || process.env.CONVENTIONAL_GITHUB_RELEASER_TOKEN
},
{ preset: 'angular' },
cb);
});
gulp.task('bump-version', (cb) => {
if (!argv.version) {
gulpUtil.log(gulpUtil.colors.red(`You must specify which version to bump to (Possible values: 'major', 'minor', and 'patch')`));
throw new Error(`Missing '--version' argument`);
}
pump(
[
gulp.src('./package.json'),
gulpBump({ type: argv.version }),
gulp.dest('./'),
], cb);
});
gulp.task('commit-changes', (cb) => {
let version = getPackageJsonVersion();
pump(
[
gulp.src('.'),
gulpGit.add(),
gulpGit.commit(`chore(release): bump version number to ${version}`)
], cb);
});
gulp.task('push-changes', (cb) => {
gulpGit.push('origin', 'master', cb);
});
gulp.task('create-new-tag', (cb) => {
let version = `v${getPackageJsonVersion()}`;
gulpGit.tag(version, `chore(release): :sparkles: :tada: create tag for version v${version}`, (error) => {
if (error) {
return cb(error);
}
gulpGit.push('origin', 'master', { args: '--tags' }, cb);
});
});
// Build and then Publish 'dist' folder to NPM
gulp.task('npm-publish', ['build'], ()=>{
return execExternalCmd('npm',`publish ${config.outputDir}`)
});
// Perfom pre-release checks (no actual release)
gulp.task('pre-release', cb => {
readyToRelease();
cb();
});
gulp.task('release', (cb) => {
gulpUtil.log('# Performing Pre-Release Checks...');
if (!readyToRelease()) {
gulpUtil.log(gulpUtil.colors.red('# Pre-Release Checks have failed. Please fix them and try again. Aborting...'));
cb();
}
else {
gulpUtil.log(gulpUtil.colors.green('# Pre-Release Checks have succeeded. Continuing...'));
runSequence(
'bump-version',
'changelog',
'commit-changes',
'push-changes',
'create-new-tag',
'github-release',
'npm-publish',
'deploy:demo',
(error) => {
if (error) {
gulpUtil.log(gulpUtil.colors.red(error.message));
} else {
gulpUtil.log(gulpUtil.colors.green('RELEASE FINISHED SUCCESSFULLY'));
}
cb(error);
});
}
});
/////////////////////////////////////////////////////////////////////////////
// Utility Tasks
/////////////////////////////////////////////////////////////////////////////
// Link 'dist' folder (create a local 'ng-scrollreveal' package that symlinks to it)
// This way, we can have the demo project declare a dependency on 'ng-scrollreveal' (as it should)
// and, thanks to 'npm link ng-scrollreveal' on demo project, be sure to always use the latest built
// version of the library ( which is in 'dist/' folder)
gulp.task('link', ()=>{
return execExternalCmd('npm', 'link', { cwd: `${config.outputDir}` });
});
gulp.task('unlink', ()=>{
return execExternalCmd('npm', 'unlink', { cwd: `${config.outputDir}` });
});
// Upload code coverage report to coveralls.io (will be triggered by Travis CI on successful build)
gulp.task('coveralls', (cb) => {
pump(
[
gulp.src(`${config.coverageDir}/coverage.lcov`),
gulpCoveralls()
], cb);
});
gulp.task('default', ['build']);
// Load additional tasks
gulpHub(['./config/gulp-tasks/*.js']);