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

ember-cli-workbox

v3.3.0

Published

Service worker generator with precaching and some basic configurable options using workbox-build

Downloads

60

Readme

ember-cli-workbox

Build Status GitHub version NPM version Dependency Status codecov Greenkeeper badge Ember Observer Score

Information

NPM

A plugin for your Ember-cli build process, giving your app offline caching as a progressive enhancement, using service workers. Ember-cli-workbox will add a service worker to your Ember App registering it on initial page load.

This addon simplify service worker registration and caching, powered by workbox-build. Workbox library automate precaching of static resources (HTML, JavaScript, CSS, and images) and handle runtime caching and fallback strategies. It allowed us to implement a performant strategy in which a static content is always served directly from the cache, and dynamic or remote resources are served from the network, with fallbacks to cached or static responses when needed.

For more details on Workbox check out:

Installation

ember install ember-cli-workbox

Dependencies

"ember-cli-uglify": "^2.0.0",

Configuration

If you need to customize ember-cli-workbox configuration you can do it like this:

// app/config/environment.js

ENV['ember-cli-workbox'] = {
  enabled: environment !== 'test',
  debug: true,
  autoRegister: true,
  importScriptsGlobPatterns: ['assets/service-workers/*.js'],
};
// ember-cli-build.js
const app = new EmberAddon(defaults, {
  'ember-cli-workbox': {
    importScriptsTransform(importScripts) {
      return importScripts.map(
        (importScript) => `https://example-cdn.com/${importScript}`
      );
    },
  },
});

| Property | Type | Description | | :-------------------------: | :--------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------: | | enabled | Boolean | Addon is enabled. Defaults true for production builds | | debug | Boolean | Log serviceworker states (registering, updating, etc) | | autoRegister | Boolean | Enable the sw registration before initializing the application | | importScriptsTransform | Function | Allows for transformation of array sent to workbox importScripts | | importScriptsGlobPatterns | Array | Define files that are going to be imported using importScripts |

You can further customize ember-cli-workbox by setting workbox configurations in your config/environment.js on in your ember-cli-build.js

Note: importScriptsTransform and workbox must be defined in your ember-cli-build.js.

//ember-cli-build.js

const app = new EmberAddon(defaults, {
  workbox: {
    globPatterns: ['**/*.{html,js,css}'],

    globDirectory: './',

    globIgnores: [],
    // ...
  },
});

| Property | Description | | :-----------------------------: | :-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | | swDest | The path to the final service worker file that will be created by the build process, relative to the build directory. Default path: ./sw.js | | globPatterns | Files matching against any of these glob patterns will be included in the precache manifest. By default sw precaches all our ember application assets that match **/*.{json,css,js,png,svg,eot,ttf,woff,jpg,gif,ico,xml,html,txt} | | globDirectory | The base directory you wish to match globPatterns against, related to the build directory. Default './' | | globIgnores | Files matching against any of these glob patterns will be excluded from the file manifest, overriding any matches from globPatterns (E.g. globIgnores: ['**\/ignored.html']) | | templatedUrls | If a URL is rendered generated based on some server-side logic, its contents may depend on multiple files or on some other unique string value. | | cacheId | An optional ID to be prepended to caches used by workbox-sw. This is primarily useful for local development where multiple sites may be served from the same http://localhost origin. Defaults to your app name (config.APP.name). | | maximumFileSizeToCacheInBytes | This value can be used to determine the maximum size of files that will be precached | | runtimeCaching | Passing in an array of objects containing urlPatterns, handlers, and potentially options that will add the appropriate code to the generated service worker to handle runtime caching. The handler values correspond the names of the strategies supported by workbox-sw (cacheFirst, cacheOnly, networkFirst, networkOnly, staleWhileRevalidate) |

runtimeCaching: [
  {
    // You can use a RegExp as the pattern:
    urlPattern: /https://api.example.com/,
    handler: 'cacheFirst',
    // Any options provided will be used when
    // creating the caching strategy.
    options: {
      cacheName: 'my-api-cache',
      cacheExpiration: {
        maxEntries: 10,
      },
    },
  },
  // ...
]

Note that importScripts parameter is overriden by this addon to include all js files on /public/assets/service-workers/* folder. If you want to change this path use importScriptsGlobPatterns option.

For more details on Workbox configuration take a look at: Workbox Google Developers.

Ember service

This addon bundles a new Ember service called service-worker. This service will register/unregister the workers when necessary.

| Property | Type | Description | | :-----------: | :-------: | :------------------------------: | | sw | Object | The navigator SW API | | isSupported | Boolean | Navigator is complatible with SW |

Methods:

  • register(swFile): Registers new service worker given a file path.
  • unregisterAll(): Unregisters all service workers.

Subscribing to events

If you are using workbox with clientsClaim: true and skipWaiting: true your serviceWorker will became active automaticatly. In this case, if you want to force reload simply do this:

// "this.serviceWorker" means the Ember service
this.serviceWorker.on('activated', () => {
  console.log('New service worker controlling the page. Forcing reload to apply new changes.');
  window.location.reload();
});

But if you want to take control of what is the state of serviceWorker, do not activate clientsClaim and skipWaiting. The recomendation is using the Ember's service-worker service (bundled with this addon) that triggers the following events:

  • error: SW not registered.
  • waiting: New SW waiting for controlling page.
  • activated: The new SW is ready to respond.
  • registrationComplete: SW successfully registered.
  • unregistrationComplete: All SW are unregistered.

Why and how to use this events?

By default, users have to close all tabs to a site in order to update a Service Worker (the Refresh button is not enough). If you make a mistake here, users will see an outdated version of your site even after refreshing. Service Workers break the Refresh button because they behave like “apps,” refusing to update while the app is still running, in order to maintain code consistency and client-side data consistency. We can write code to notify users when a new version is available.

This addon make it easy for you and implements google recommendation. Basically, what you have to do is subscribing to the event waiting. When event is triggered, send a message to sw in order to launch skipWaiting + clients.claim on it to turn it active (you can do this just calling forceActivate method on serviceWorkerService). When service worker became active it will send a message "reload-window" and "newSWActive" will be triggered.

Example:

// <my-app>/mixins/service-worker-states.js

import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';

export default class MyRoute extends Route {
  @service serviceWorker;

  async beforeModel() {
    await super.beforeModel(...arguments);

    // Do not call this event twice!
    this.subscribeToSWEvents();
  }

  subscribeToSWEvents() {
    this.serviceWorker.on('activated', (reg) => {
      window.alert('Content is now available offline!');
    });

    this.serviceWorker.on('waiting', (reg) => {
      if (window.confirm('New version available! Refresh?')) {
        sw.forceActivate(reg);
      }
    });

    this.serviceWorker.on('updated', () => {
      window.location.reload();
    });
  }
}

Prevent caching lazy engines

By default, this addons precaches everything, that means all the lazy engines will be precached in your service worker. To prevent precaching it, just exclude the engine-dist in the addon config:

var ENV = {
  workbox: {
    globIgnores: ['engines-dist/**/*'],

    runtimeCaching: [
      {
        urlPattern: /engines-dist/,
        handler: 'networkFirst',
      },
    ],
  },
};

Debugging serviceWorker generation on build

$ DEBUG=ember-cli:workbox ember s

Future improvements

ember-cli-workbox currently do not implement workboxBuild.injectManifest() feature, only works generating a new serviceworker.

What is injectManifest feature?

If you have an existing serviceWorker, workbox-build can modify it to inject the manifest file to precache our static files. Basically you should have a placeholder array which is populated automatically by workboxBuild.injectManifest().

// my existing service worker
workboxSW.precache([]);

Sometimes you'll need more control over what is cached, strategies used and custom code inside the server worker. You can do this by setting your own service worker and using the WorkboxSW object directly.

Contributing

We're thankful to the community for contributing any improvements.

Do not forget to follow our eslint rules and make test for the new functionalities/fixes.