forked from andreasbm/web-config
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rollup-plugin-workbox.ts
74 lines (64 loc) · 1.98 KB
/
rollup-plugin-workbox.ts
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
import colors from "colors";
import { OutputBundle, OutputOptions } from "rollup";
import { generateSW, injectManifest } from "workbox-build";
export type WorkboxConfig = any;
export type GenerateServiceWorkerType = "generateSW" | "injectManifest";
export enum GenerateServiceWorkerKind {
generateSw = "generateSW",
injectManifest = "injectManifest"
}
export interface IRollupPluginWorkboxConfig {
mode: GenerateServiceWorkerType;
verbose: boolean;
timeout: number;
workboxConfig: WorkboxConfig;
}
/**
* Default configuration for the workbox rollup plugin.
*/
const defaultConfig: IRollupPluginWorkboxConfig = {
mode: GenerateServiceWorkerKind.generateSw,
verbose: true,
timeout: 2000,
workboxConfig: {}
};
/**
* Returns the correct method to for generating the Service Worker.
* @param mode
*/
function workboxFactory(mode: GenerateServiceWorkerType): typeof generateSW | typeof injectManifest {
switch (mode) {
case GenerateServiceWorkerKind.generateSw:
return generateSW;
case GenerateServiceWorkerKind.injectManifest:
return injectManifest;
}
throw new Error(`[workbox] - The mode "${mode} is not valid"`);
}
/**
* A Rollup plugin that uses workbox to generate a service worker.
* @param config
*/
export function workbox(config: Partial<IRollupPluginWorkboxConfig> = {}) {
const { workboxConfig, mode, verbose, timeout } = { ...defaultConfig, ...config };
// Ensure a workbox config exists
if (workboxConfig == null) {
throw new Error(`[workbox] - The workboxConfig needs to be defined`);
}
return {
name: "workbox",
generateBundle: async (outputOptions: OutputOptions, bundle: OutputBundle, isWrite: boolean): Promise<void> => {
if (!isWrite) return;
try {
setTimeout(async () => {
await workboxFactory(mode)(workboxConfig);
}, timeout);
await workboxFactory(mode)(workboxConfig);
} catch (ex) {
if (verbose) {
console.log(colors.red(`[workbox] - The Service Worker could not be generated: "${ex.message}"`));
}
}
}
};
}