{"id":13807742,"url":"https://github.com/BBVAEngineering/ember-cli-workbox","last_synced_at":"2025-05-14T00:32:00.422Z","repository":{"id":26653977,"uuid":"108830512","full_name":"BBVAEngineering/ember-cli-workbox","owner":"BBVAEngineering","description":"Offline caching as a progressive enhancement using service workers","archived":false,"fork":false,"pushed_at":"2024-07-30T11:02:20.000Z","size":6267,"stargazers_count":20,"open_issues_count":25,"forks_count":11,"subscribers_count":9,"default_branch":"master","last_synced_at":"2025-05-10T13:42:21.273Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/BBVAEngineering.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2017-10-30T09:41:18.000Z","updated_at":"2024-02-19T14:40:43.000Z","dependencies_parsed_at":"2025-04-10T08:14:58.902Z","dependency_job_id":"56bae26d-d153-4f85-9edd-5ab9e86c999d","html_url":"https://github.com/BBVAEngineering/ember-cli-workbox","commit_stats":{"total_commits":180,"total_committers":15,"mean_commits":12.0,"dds":0.8,"last_synced_commit":"94766390df47f497a56262faad2d0cc70adb4e3d"},"previous_names":[],"tags_count":26,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BBVAEngineering%2Fember-cli-workbox","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BBVAEngineering%2Fember-cli-workbox/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BBVAEngineering%2Fember-cli-workbox/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BBVAEngineering%2Fember-cli-workbox/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/BBVAEngineering","download_url":"https://codeload.github.com/BBVAEngineering/ember-cli-workbox/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254046389,"owners_count":22005581,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-04T01:01:29.751Z","updated_at":"2025-05-14T00:31:55.407Z","avatar_url":"https://github.com/BBVAEngineering.png","language":"JavaScript","readme":"# ember-cli-workbox\n\n[![Build Status](https://travis-ci.org/BBVAEngineering/ember-cli-workbox.svg?branch=master)](https://travis-ci.org/BBVAEngineering/ember-cli-workbox)\n[![GitHub version](https://badge.fury.io/gh/BBVAEngineering%2Fember-cli-workbox.svg)](https://badge.fury.io/gh/BBVAEngineering%2Fember-cli-workbox)\n[![NPM version](https://badge.fury.io/js/ember-cli-workbox.svg)](https://badge.fury.io/js/ember-cli-workbox)\n[![Dependency Status](https://david-dm.org/BBVAEngineering/ember-cli-workbox.svg)](https://david-dm.org/BBVAEngineering/ember-cli-workbox)\n[![codecov](https://codecov.io/gh/BBVAEngineering/ember-cli-workbox/branch/master/graph/badge.svg)](https://codecov.io/gh/BBVAEngineering/ember-cli-workbox)\n[![Greenkeeper badge](https://badges.greenkeeper.io/BBVAEngineering/ember-cli-workbox.svg)](https://greenkeeper.io/)\n[![Ember Observer Score](https://emberobserver.com/badges/ember-cli-workbox.svg)](https://emberobserver.com/addons/ember-cli-workbox)\n\n## Information\n\n[![NPM](https://nodei.co/npm/ember-cli-workbox.png?downloads=true\u0026downloadRank=true)](https://nodei.co/npm/ember-cli-workbox/)\n\nA 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.\n\nThis addon simplify service worker registration and caching, powered by [workbox-build](https://www.npmjs.com/package/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.\n\nFor more details on Workbox check out:\n\n- [Workbox Google Developers](https://developers.google.com/web/tools/workbox/)\n- [Service Workers cookbook](https://serviceworke.rs/)\n\n## Installation\n\n`ember install ember-cli-workbox`\n\n## Dependencies\n\n\"ember-cli-uglify\": \"^2.0.0\",\n\n## Configuration\n\nIf you need to customize **ember-cli-workbox configuration** you can do it like this:\n\n```javascript\n// app/config/environment.js\n\nENV['ember-cli-workbox'] = {\n  enabled: environment !== 'test',\n  debug: true,\n  autoRegister: true,\n  importScriptsGlobPatterns: ['assets/service-workers/*.js'],\n};\n```\n\n```javascript\n// ember-cli-build.js\nconst app = new EmberAddon(defaults, {\n  'ember-cli-workbox': {\n    importScriptsTransform(importScripts) {\n      return importScripts.map(\n        (importScript) =\u003e `https://example-cdn.com/${importScript}`\n      );\n    },\n  },\n});\n```\n\n|          Property           |    Type    |                                                                            Description                                                                             |\n| :-------------------------: | :--------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------: |\n|          `enabled`          | `Boolean`  |                                                      Addon is enabled. Defaults `true` for production builds                                                       |\n|           `debug`           | `Boolean`  |                                                       Log serviceworker states (registering, updating, etc)                                                        |\n|       `autoRegister`        | `Boolean`  |                                                   Enable the sw registration before initializing the application                                                   |\n|  `importScriptsTransform`   | `Function` | Allows for transformation of array sent to workbox [importScripts](https://developers.google.com/web/tools/workbox/modules/workbox-build#generateSW-importScripts) |\n| `importScriptsGlobPatterns` |  `Array`   |  Define files that are going to be imported using [importScripts](https://developers.google.com/web/tools/workbox/modules/workbox-build#generateSW-importScripts)  |\n\nYou can further customize ember-cli-workbox by setting **workbox configurations** in your `config/environment.js` on in your `ember-cli-build.js`\n\n_Note_: `importScriptsTransform` and `workbox` must be defined in your `ember-cli-build.js`.\n\n```javascript\n//ember-cli-build.js\n\nconst app = new EmberAddon(defaults, {\n  workbox: {\n    globPatterns: ['**/*.{html,js,css}'],\n\n    globDirectory: './',\n\n    globIgnores: [],\n    // ...\n  },\n});\n```\n\n|            Property             |                                                                                                                                                                                                                       Description                                                                                                                                                                                                                       |\n| :-----------------------------: | :-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: |\n|            `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`                                                                                                                                                      |\n|         `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}`                                                                                                           |\n|         `globDirectory`         |                                                                                                                                                                         The base directory you wish to match globPatterns against, related to the build directory. Default './'                                                                                                                                                                         |\n|          `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']`)                                                                                                                                      |\n|         `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.                                                                                                                                                     |\n|            `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).                                                                                                            |\n| `maximumFileSizeToCacheInBytes` |                                                                                                                                                                                  This value can be used to determine the maximum size of files that will be precached                                                                                                                                                                                   |\n|        `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](https://developers.google.com/web/tools/workbox/reference-docs/latest/module-workbox-sw.Strategies) supported by workbox-sw (cacheFirst, cacheOnly, networkFirst, networkOnly, staleWhileRevalidate) |\n\n```javascript\nruntimeCaching: [\n  {\n    // You can use a RegExp as the pattern:\n    urlPattern: /https://api.example.com/,\n    handler: 'cacheFirst',\n    // Any options provided will be used when\n    // creating the caching strategy.\n    options: {\n      cacheName: 'my-api-cache',\n      cacheExpiration: {\n        maxEntries: 10,\n      },\n    },\n  },\n  // ...\n]\n```\n\nNote 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.\n\n\u003e For more details on Workbox configuration take a look at: [Workbox Google Developers](https://developers.google.com/web/tools/workbox/reference-docs/latest/module-workbox-build).\n\n## Ember service\n\nThis addon bundles a new Ember service called `service-worker`.\nThis service will register/unregister the workers when necessary.\n\n|   Property    |   Type    |           Description            |\n| :-----------: | :-------: | :------------------------------: |\n|     `sw`      | `Object`  |       The navigator SW API       |\n| `isSupported` | `Boolean` | Navigator is complatible with SW |\n\n**Methods:**\n\n- `register(swFile)`: Registers new service worker given a file path.\n- `unregisterAll()`: Unregisters all service workers.\n\n## Subscribing to events\n\nIf you are using workbox with `clientsClaim: true` and `skipWaiting: true` your serviceWorker will became active automaticatly.\nIn this case, if you want to force reload simply do this:\n\n```JavaScript\n// \"this.serviceWorker\" means the Ember service\nthis.serviceWorker.on('activated', () =\u003e {\n  console.log('New service worker controlling the page. Forcing reload to apply new changes.');\n  window.location.reload();\n});\n```\n\nBut if you want to take control of what is the state of serviceWorker, do not activate `clientsClaim` and `skipWaiting`.\nThe recomendation is using the Ember's `service-worker` service (bundled with this addon) that triggers the following events:\n\n- `error`: SW not registered.\n- `waiting`: New SW waiting for controlling page.\n- `activated`: The new SW is ready to respond.\n- `registrationComplete`: SW successfully registered.\n- `unregistrationComplete`: All SW are unregistered.\n\n### Why and how to use this events?\n\nBy default, users have to close all tabs to a site in order to update a Service Worker (the Refresh button is not enough).\nIf you make a mistake here, **users will see an outdated version of your site** even after refreshing.\nService 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.\n\nThis addon make it easy for you and implements [google recommendation](https://developers.google.com/web/tools/workbox/guides/advanced-recipes#offer_a_page_reload_for_users).\nBasically, 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.\n\n**Example:**\n\n```javascript\n// \u003cmy-app\u003e/mixins/service-worker-states.js\n\nimport Route from '@ember/routing/route';\nimport { inject as service } from '@ember/service';\n\nexport default class MyRoute extends Route {\n  @service serviceWorker;\n\n  async beforeModel() {\n    await super.beforeModel(...arguments);\n\n    // Do not call this event twice!\n    this.subscribeToSWEvents();\n  }\n\n  subscribeToSWEvents() {\n    this.serviceWorker.on('activated', (reg) =\u003e {\n      window.alert('Content is now available offline!');\n    });\n\n    this.serviceWorker.on('waiting', (reg) =\u003e {\n      if (window.confirm('New version available! Refresh?')) {\n        sw.forceActivate(reg);\n      }\n    });\n\n    this.serviceWorker.on('updated', () =\u003e {\n      window.location.reload();\n    });\n  }\n}\n```\n\n## Prevent caching lazy engines\n\nBy default, this addons precaches everything, that means all the lazy engines will be precached in your service worker.\nTo prevent precaching it, just exclude the `engine-dist` in the addon config:\n\n```javascript\nvar ENV = {\n  workbox: {\n    globIgnores: ['engines-dist/**/*'],\n\n    runtimeCaching: [\n      {\n        urlPattern: /engines-dist/,\n        handler: 'networkFirst',\n      },\n    ],\n  },\n};\n```\n\n## Debugging serviceWorker generation on build\n\n```bash\n$ DEBUG=ember-cli:workbox ember s\n```\n\n## Future improvements\n\n`ember-cli-workbox` currently do not implement `workboxBuild.injectManifest()` feature, only works generating a new serviceworker.\n\n**What is injectManifest feature?**\n\nIf you have an existing serviceWorker, `workbox-build` can modify it to inject the manifest file to precache our static files.\nBasically you should have a placeholder array which is populated automatically by `workboxBuild.injectManifest()`.\n\n```javascript\n// my existing service worker\nworkboxSW.precache([]);\n```\n\nSometimes 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.\n\n## Contributing\n\nWe're thankful to the community for contributing any improvements.\n\nDo not forget to follow our `eslint` rules and make test for the new functionalities/fixes.\n","funding_links":[],"categories":["Packages"],"sub_categories":["Service Workers"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FBBVAEngineering%2Fember-cli-workbox","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FBBVAEngineering%2Fember-cli-workbox","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FBBVAEngineering%2Fember-cli-workbox/lists"}