npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

inject-sw

v1.1.1

Published

CLI & helper function to generate service worker files to precache assets and inject service worker code snippet into an html file

Downloads

22

Readme

inject-sw

inject-sw @ npm

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.

<script>
// Check that service workers are supported
if ('serviceWorker' in navigator) {
  // Use the window load event to keep the page load performant
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('sw.js');
  });
}
</script>

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: argv.o.startsWith('/dev')
    ? path.join(process.cwd(), 'sw.js')
    : path.resolve(argv.o, '../sw.js'),
  // Read assets from the directory of the input HTML file, fallback to current
  // directory if input is /dev/stdin.
  globDirectory: argv.i.startsWith('/dev')
    ? process.cwd()
    : path.resolve(argv.i, '..'),
  // 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 } = require('inject-sw');

injectSWHtml(html, minify = false, swUrl = 'sw.js');

/* See https://developers.google.com/web/tools/workbox/reference-docs/latest/module-workbox-build#.generateSW */
const config = {};
generateSW(config).then(result => {
  console.dir(result);
})

Code Example:

const { injectSWHtml, generateSW } = require('inject-sw');
const html = '<!doctype html><html><head><title>Hello World</title></head><body>Morning World</body></html>';
const injectedHTML = injectSWHtml(html, true, '/sw.js');
console.log(injectedHTML);

generateSW({
  "globDirectory": "dist/",
  "globPatterns": [
    "**/*.{html,css,js,json}",
    "**/*.{jpg,png,svg}"
  ],
  "swDest": "dist/sw.js"
})

Filename as arguments

API:

const injectSWFile = require('inject-sw/cli');
injectSWFile(input, output, minify, swConfig, swUrl = 'sw.js');

Code Example:

const injectSWFile = require('inject-sw/cli');

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';
injectSWFile(inputFilename, outputFilename, minify, swConfig, swUrl);

Debug

Set environment variable DEBUG to inject-sw.

LICENSE

MIT