forked from MurhafSousli/ngx-bar-rating
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gulpfile.js
324 lines (266 loc) · 9.86 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
/**
* @Author: @MurhafSousli
*/
const gulp = require('gulp');
/** To log like console.log().. */
const gutil = require('gulp-util');
/** del to remove dist directory */
const del = require('del');
/** load templates and styles in ng2 components */
const embedTemplates = require('gulp-inline-ng2-template');
/** TSLint checker */
const tslint = require('gulp-tslint');
/** Sass style */
const postcss = require('postcss');
const sass = require('node-sass');
const autoprefixer = require('autoprefixer');
const cssnano = require('cssnano');
const scss = require('postcss-scss');
const stripInlineComments = require('postcss-strip-inline-comments');
/** External command runner */
const exec = require('child_process').exec;
const spawn = require('child_process').spawn;
const process = require('process');
/**OS Access */
const os = require('os');
/** File Access */
const fs = require('fs');
const file = require('gulp-file');
const path = require('path');
/** To properly handle pipes on error */
const pump = require('pump');
/** To upload code coverage to coveralls */
const coveralls = require('gulp-coveralls');
/** To order tasks */
const runSequence = require('run-sequence');
/** To bundle the library with Rollup */
const gulpRollup = require('gulp-better-rollup');
const rollupNodeResolve = require('rollup-plugin-node-resolve');
const rollupUglify = require('rollup-plugin-uglify');
/** To compile themes scss to css */
const gulpSass = require('gulp-sass');
const LIBRARY_NAME = 'ngx-bar-rating';
const config = {
allTs: 'src/**/!(*.spec).ts',
allSass: 'src/**/*.scss',
allHtml: 'src/**/*.html',
themes: 'src/themes/**/*.scss',
demoDir: 'demo/',
outputDir: 'dist/',
coverageDir: 'coverage/'
};
//Helper functions
function platformPath(path) {
return /^win/.test(os.platform()) ? `${path}.cmd` : path;
}
function startKarmaServer(isTddMode, hasCoverage, done) {
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, done).start();
}
function execCallback(gulpDone) {
return (error, stdout, stderr) => {
if (stderr) {
gutil.log(gutil.colors.red(stderr));
}
if (stdout) {
gutil.log(gutil.colors.green(stdout));
}
// execute callback when its done
if (gulpDone) {
gulpDone();
}
}
}
// Clean Tasks
gulp.task('clean:dist', () => {
return del(config.outputDir);
});
gulp.task('clean:coverage', () => {
return del(config.coverageDir);
});
gulp.task('clean', ['clean:dist', 'clean:coverage']);
// TsLint the source files
gulp.task('lint', (cb) => {
pump([
gulp.src(config.allTs),
tslint({ formatter: "verbose" }),
tslint.report()
], cb);
});
// Compile Sass to css and Inline templates and styles in ng2 components
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);
});
}
}
};
// Inline templates and styles in ng2 components
gulp.task('inline-templates', (cb) => {
const options = {
base: '/src',
target: 'es5',
styleProcessor: styleProcessor,
useRelativePaths: true
};
pump(
[
gulp.src(config.allTs),
embedTemplates(options),
gulp.dest(`${config.outputDir}/inlined`)
],
cb);
});
// Compile inlined TS files with Angular Compiler (ngc)
gulp.task('ngc', (cb) => {
const executable = path.join(__dirname, platformPath('/node_modules/.bin/ngc'));
const ngc = exec(`${executable} -p ./tsconfig-aot.json`, (err) => {
if (err) return cb(err); // return error
del(`${config.outputDir}/inlined`); //delete temporary *.ts files with inlined templates and styles
cb();
}).stdout.on('data', (data) => console.log(data));
});
// 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);
});
// Prepare 'dist' folder for publication to NPM
gulp.task('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'] = LIBRARY_NAME;
//only copy needed properties from project's package json
fieldsToCopy.forEach((field) => { targetPkgJson[field] = pkgJson[field]; });
targetPkgJson['main'] = `bundles/ngx-bar-rating.umd.js`;
targetPkgJson['module'] = 'index.js';
targetPkgJson['typings'] = 'index.d.ts';
// defines project's dependencies as 'peerDependencies' for final users
targetPkgJson.peerDependencies = {};
Object.keys(pkgJson.dependencies).forEach((dependency) => {
if (dependency.startsWith('@angular/')) {
// narrow version of @angular packages to address bug with JSONP inroduced in [2.4.6, 2.4.8[ && [4.0.0-beta.6, 4.0.0-beta.8[
// see https://github.com/angular/angular/pull/13219 and changelog
targetPkgJson.peerDependencies[dependency] = `>=2.0.0 <2.4.6 || >=2.4.8 <4.0.0-beta.6 || >=4.0.0-beta.8`;
}
else {
targetPkgJson.peerDependencies[dependency] = `^${pkgJson.dependencies[dependency]}`;
}
});
// copy the needed additional files in the 'dist' folder
pump(
[
gulp.src(['README.md', 'LICENSE', 'CHANGELOG.md']),
file('package.json', JSON.stringify(targetPkgJson, null, 2)),
gulp.dest(config.outputDir)
],
cb);
});
// Bundles the library as UMD bundle using RollupJS
gulp.task('bundle', () => {
const globals = {
// Angular dependencies
'@angular/core': 'ng.core',
'@angular/common': 'ng.common',
'@angular/forms': 'ng.forms'
};
const rollupOptions = {
context: 'this',
external: Object.keys(globals),
plugins: [
rollupNodeResolve({ module: true }),
rollupUglify()
]
};
const rollupGenerateOptions = {
// Keep the moduleId empty because we don't want to force developers to a specific moduleId.
moduleId: '',
moduleName: 'ngxBarRating', //require for 'umd' bundling, must be a valid js identifier, see rollup/rollup/issues/584
format: 'umd',
globals,
dest: 'ngx-bar-rating.umd.js'
};
return gulp.src(`${config.outputDir}/index.js`)
.pipe(gulpRollup(rollupOptions, rollupGenerateOptions))
.pipe(gulp.dest(`${config.outputDir}/bundles`));
});
// Serve the demo application
gulp.task('demo', (done) => {
const executable = path.join(__dirname, platformPath('demo/node_modules/.bin/ng'));
const ngServe = spawn(`${executable}`, ['serve'], { cwd: `${config.demoDir}` }); // run 'ng serve' from there
ngServe.stdout.pipe(process.stdout);
ngServe.stderr.pipe(process.stderr);
});
// Link 'dist' folder (create a local 'ngx-bar-rating' package that symlinks to it)
// This way, we can have the demo project declare a dependency on 'ngx-bar-rating' (as it should)
// and, thanks to 'npm link ngx-bar-rating' on demo project, be sure to always use the latest built
// version of the library ( which is in 'dist/' folder)
gulp.task('link', (done) => {
exec('npm link', { cwd: `${config.outputDir}` }, execCallback(done)); // run 'npm link' from 'dist' folder
});
// Upload code coverage report to coveralls.io (will be triggered by Travis CI on successful build)
gulp.task('coveralls', () => {
return gulp.src(`${config.coverageDir}/coverage.lcov`)
.pipe(coveralls());
});
// Lint, Sass to css, Inline templates & Styles and Compile
gulp.task('compile', (cb) => {
runSequence('lint', 'inline-templates', 'ngc', cb);
});
// Watch changes on (*.ts, *.sass, *.html) and Compile
gulp.task('watch', () => {
gulp.watch([config.allTs, config.allHtml, config.allSass], ['compile']);
});
// Copy themes folder
gulp.task('themes', () => {
const sassOptions = {
outputStyle: 'compressed'
};
gulp.src([config.themes])
.pipe(gulpSass(sassOptions))
.pipe(gulp.dest(`${config.outputDir}/themes`));
});
// Build the 'dist' folder (without publishing it to NPM)
gulp.task('build', ['clean'], (cb) => {
runSequence('compile', 'package', 'bundle', 'themes', cb);
});
// Build and then Publish 'dist' folder to NPM
gulp.task('publish', ['build'], (done) => {
// run npm publish terminal command to publish the 'dist' folder only
exec(`npm publish ${config.outputDir}`, execCallback(done));
});
gulp.task('default', ['build']);