-
Notifications
You must be signed in to change notification settings - Fork 0
/
gulpfile.js
89 lines (78 loc) · 2.42 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
var gulp = require('gulp');
var del = require('del');
var swPrecache = require('sw-precache');
var $ = require('gulp-load-plugins')();
var path = require('path');
var webpack = require('webpack');
var gulpWebpack = require('webpack-stream');
var runSequence = require('run-sequence');
var express = require('express');
var rootDir = 'dist';
gulp.task('clean', function () {
return del(['dist/**/*', '!dist'])
});
gulp.task('build', function (done) {
let flag = false;
process.argv.forEach(function (item) {
if (item === '--precache') {
flag = true;
} else {
flag = false;
}
});
if (flag) {
runSequence('clean', 'webpack', 'precache', done);
} else {
runSequence('clean', 'webpack', done);
}
});
gulp.task('webpack', function () {
return gulp.src('src/index.js')
.pipe(gulpWebpack(require('./webpack.prod.config'), webpack))
.pipe(gulp.dest(rootDir));
});
gulp.task('precache', function (cb) {
writeServiceWorkerFile(rootDir, true, cb);
});
gulp.task('server', function () {
runExpress(4000, rootDir);
});
function runExpress(port, rootDir) {
var app = express();
app.use(express.static(rootDir));
var server = app.listen(port, function() {
var host = server.address().address;
var port = server.address().port;
console.log('Server running at http://%s:%s', host, port);
});
}
function writeServiceWorkerFile(rootDir, handleFetch, callback) {
var config = {
// If handleFetch is false (i.e. because this is called from generate-service-worker-dev), then
// the service worker will precache resources but won't actually serve them.
// This allows you to test precaching behavior without worry about the cache preventing your
// local changes from being picked up during the development cycle.
handleFetch: handleFetch,
logger: $.util.log,
staticFileGlobs: [
rootDir + '/css/**.css',
rootDir + '/**.html',
rootDir + '/js/**.js'
],
runtimeCaching: [
{
// See https://github.com/GoogleChrome/sw-toolbox#methods
urlPattern: /https:\/\/api.heweather.com\/x3\/weather/,
handler: 'networkFirst',
},
{
urlPattern: /\/images\//,
handler: 'cacheFirst'
}
],
stripPrefix: rootDir + '/',
// verbose defaults to false, but for the purposes of this demo, log more.
verbose: true
};
swPrecache.write(path.join(rootDir, 'service-worker.js'), config, callback);
}