Skip to content
This repository has been archived by the owner on Dec 7, 2021. It is now read-only.

add service worker flag to build command #534

Merged
merged 6 commits into from
Jan 13, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 28 additions & 22 deletions src/build/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,23 +16,21 @@ import * as del from 'del';
import * as path from 'path';
import * as logging from 'plylog';
import {dest} from 'vinyl-fs';


import mergeStream = require('merge-stream');
import {PolymerProject, addServiceWorker} from 'polymer-build';
import {PolymerProject, addServiceWorker, SWConfig} from 'polymer-build';

import {OptimizeOptions, getOptimizeStreams} from './optimize-streams';

import {ProjectConfig} from 'polymer-project-config';
import {PrefetchTransform} from './prefetch';
import {waitFor, pipeStreams} from './streams';
import {parsePreCacheConfig} from './sw-precache';
import {loadServiceWorkerConfig} from './load-config';

const logger = logging.getLogger('cli.build.build');

const buildDirectory = 'build/';

export interface BuildOptions extends OptimizeOptions {
addServiceWorker?: boolean;
swPrecacheConfig?: string;
insertPrefetchLinks?: boolean;
bundle?: boolean;
Expand All @@ -43,8 +41,6 @@ export async function build(
const optimizeOptions:
OptimizeOptions = {css: options.css, js: options.js, html: options.html};
const polymerProject = new PolymerProject(config);
const swPrecacheConfig = path.resolve(
config.root, options.swPrecacheConfig || 'sw-precache-config.js');

logger.info(`Deleting build/ directory...`);
await del([buildDirectory]);
Expand Down Expand Up @@ -84,29 +80,39 @@ export async function build(
logger.info('Generating build/ directory...');
});

// Finish the build stream by piping it into the final build directory.
buildStream = buildStream.pipe(dest(buildDirectory));


// While the build is in progress, parse the sw precache config
const swConfig = await parsePreCacheConfig(swPrecacheConfig);
if (swConfig) {
logger.debug(`Service worker config found`, swConfig);
} else {
logger.debug(`No service worker configuration found at ${swPrecacheConfig
}, continuing with defaults`);
// If a service worker was requested, parse the service worker config file
// while the build is in progress. Loading the config file during the build
// saves the user ~300ms vs. loading it afterwards.
const swPrecacheConfigPath = path.resolve(
config.root, options.swPrecacheConfig || 'sw-precache-config.js');
let swConfig: SWConfig|null = null;
if (options.addServiceWorker) {
swConfig = await loadServiceWorkerConfig(swPrecacheConfigPath);
}

// Now that the build stream has been set up, wait for it to complete.
// There is nothing left to do, so wait for the build stream to complete.
await waitFor(buildStream);

// addServiceWorker() reads from the file system, so we need to wait for
// the build stream to finish writing to disk before calling it.
await addServiceWorker({
buildRoot: buildDirectory,
project: polymerProject,
swPrecacheConfig: swConfig || undefined,
bundled: options.bundle,
});
if (options.addServiceWorker) {
logger.info(`Generating service worker...`);
if (swConfig) {
logger.debug(`Service worker config found`, swConfig);
} else {
logger.debug(`No service worker configuration found at ` +
`${swPrecacheConfigPath}, continuing with defaults`);
}
await addServiceWorker({
buildRoot: buildDirectory,
project: polymerProject,
swPrecacheConfig: swConfig || undefined,
bundled: options.bundle,
});
}

logger.info('Build complete!');
}
4 changes: 2 additions & 2 deletions src/build/sw-precache.ts → src/build/load-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ import * as fs from 'fs';
import * as logging from 'plylog';
import {SWConfig} from 'polymer-build';

let logger = logging.getLogger('cli.build.sw-precache');
let logger = logging.getLogger('cli.build.load-config');

export function parsePreCacheConfig(configFile: string):
export function loadServiceWorkerConfig(configFile: string):
Promise<SWConfig|null> {
return new Promise<SWConfig|null>((resolve, _reject) => {
fs.stat(configFile, (statError) => {
Expand Down
15 changes: 13 additions & 2 deletions src/commands/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,11 +59,21 @@ export class BuildCommand implements Command {
'a minimum set of bundles. Useful for reducing the number of ' +
'requests needed to serve your application.'
},
{
name: 'add-service-worker',
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why rename this flag? The file is still sw-precache specific?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

until we support more than sw-precache, we may want to name this something sw-precache specific. maybe --add-sw-precache or --use-sw-precache

type: Boolean,
description: 'Generate a service worker for your application to ' +
'cache all files and assets on the client.'
},
{
name: 'sw-precache-config',
type: String,
defaultValue: 'sw-precache-config.js',
description: 'Path to an sw-precache configuration to be ' +
'used for service worker generation.'
description: 'Path to a file that exports configuration options for ' +
'the generated service worker. These options match those supported ' +
'by the sw-precache library. See ' +
'https://github.com/GoogleChrome/sw-precache#options-parameter ' +
'for a list of all supported options.'
},
{
name: 'insert-prefetch-links',
Expand All @@ -80,6 +90,7 @@ export class BuildCommand implements Command {
const build = require('../build/build').build;

let buildOptions: BuildOptions = {
addServiceWorker: options['add-service-worker'],
swPrecacheConfig: options['sw-precache-config'],
insertPrefetchLinks: options['insert-prefetch-links'],
bundle: options['bundle'],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,15 @@
const assert = require('chai').assert;
const path = require('path');

const precache = require('../../../lib/build/sw-precache');
const loadServiceWorkerConfig = require('../../../lib/build/load-config').loadServiceWorkerConfig;

suite('sw-precache', () => {
suite('parsePreCacheConfig()', () => {
test('should parse a js file', (done) => {
const configFile = path.resolve(__dirname, 'precache', 'config.js');
precache.parsePreCacheConfig(configFile).then((config) => {
suite('load-config', () => {
suite('loadServiceWorkerConfig()', () => {
test('should parse the given js file', (done) => {
const configFile = path.resolve(__dirname, '../', 'fixtures', 'service-worker-config.js');
loadServiceWorkerConfig(configFile).then((config) => {
assert.ok(config);
assert.property(config, 'staticFileGlobs');
assert.deepEqual(config.staticFileGlobs, ['*']);
done();
})
});
Expand Down
10 changes: 0 additions & 10 deletions test/unit/build/precache/static/fizz.html

This file was deleted.

1 change: 0 additions & 1 deletion test/unit/build/precache/static/foo.js

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
module.exports = {
staticFileGlobs: ['*'],
}
}