inject-sw
A CLI & helper function to generate service worker files to precache assets and inject service worker code snippet into an html file using Workbox.
The following is the code snippet to be inserted as the last item of <body>
. It can optionally be inserted as minified.
Install as CLI
npm i -g inject-sw
Usage
inject-sw [--sw-config <config_file>] [--sw-url <url>] [ [-i|--input]
<input_file> ] [ [-o|--output] <output_file> ] [--minify]
Options:
--help Show help [boolean]
--version Show version number [boolean]
--sw-config Config file for service worker generation. Defaults to
workbox-config.js, with fallback to sane defaults.
--sw-url URL for generated sw.js [default: "sw.js"]
-o, --output path to output html file [default: "/dev/stdout"]
--minify minify the service worker code snippet[boolean] [default: false]
-i, --input [default: "/dev/stdin"]
And the service worker config file defaults to the following:
// Write to the directory of the HTML file, fallback to current directory // if output is /dev/stdout. swDest: argvo ? path : path // Read assets from the directory of the input HTML file, fallback to current // directory if input is /dev/stdin. globDirectory: argvi ? process : path // Cache every single file by default globPatterns: '**/*' // Except files in node_modules globIgnores: 'node_modules/**/*' '**/*.map'
Examples
# Reads from src/index.html and writes to dist/index.html inject-sw -i src/index.html -o dist/index.html # Write in-place inject-sw -i index.html -o index.html # Specify --minify to minify the service worker code snippet # (Note that it does not minify other parts of the html page) # Input and output can be specified as positional arguments inject-sw --minify a.html b.html # Specify the config and the URL for service worker inject-sw --sw-config workbox-config.js --sw-url /sw.js -i index.html -o index.html
Install as package dependency
npm i inject-sw
Usage & Examples
HTML string as arguments
API:
const injectSWHtml generateSW = ; ; /* See https://developers.google.com/web/tools/workbox/reference-docs/latest/module-workbox-build#.generateSW */const config = {};
Code Example:
const injectSWHtml generateSW = ;const html = '<!doctype html><html><head><title>Hello World</title></head><body>Morning World</body></html>';const injectedHTML = ;console;
Filename as arguments
API:
const injectSWFile = ;;
Code Example:
const injectSWFile = ; const inputFilename = 'a.html';const outputFilename = 'b.html';const minify = true;const swConfig = "globDirectory": "dist/" "globPatterns": "**/*.{html,css,js,json}" "**/*.{jpg,png,svg}" "swDest": "dist/sw.js";const swUrl = '/sw.js';;
Debug
Set environment variable DEBUG
to inject-sw
.