Git Product home page Git Product logo

offline-plugin's Introduction

offline-plugin for webpack

This plugin is intended to provide offline experience for webpack projects. It uses ServiceWorker and AppCache as a fallback under the hood. Simply include this plugin in your webpack.config, and the accompanying runtime in your client script, and your project will became offline ready by caching all (or some) output assets.

Install

npm install offline-plugin [--save-dev]

Setup

First, instantiate the plugin with options in your webpack.config:

// webpack.config.js example

var OfflinePlugin = require('offline-plugin');

module.exports = {
  // ...

  plugins: [
    // ... other plugins

    new OfflinePlugin({
      // All options are optional
      caches: 'all',
      scope: '/',
      updateStrategy: 'all',
      version: 'v1',

      ServiceWorker: {
        output: 'sw.js'
      },

      AppCache: {
        directory: 'appcache/'
      }
    })
  ]
  // ...
}

Then, install the runtime in your client script:

require('offline-plugin/runtime').install();

Options

All options are optional and offline-plugin could be used without specifying them. Also see full list of default options here.

  • caches: 'all' | Object. Tells to the plugin what to cache and how. Default: 'all'.
    • all: means that everything (all the webpack output assets) will be cached in main cache.
    • Object: Object with 3 possible Array sections (properties). All sections are optional and default empty (no assets added). Use special keyword :rest: to match all unused/uncached assets. To match multiple assets or assets with dynamic names, use pattern matching. Any section can contain any assets, not only those which are generated by the webpack build. However, "pattern matching" is executed only against generated assets. When external asset is included you will receive warning about it (missing from generated assets) unless it's explicitly marked as external via externals option.
      • main cache. Assets listed in this section are cached first (via install event in ServiceWorker) and if caching of this section fails -- no assets are cached at all. Hence, it should contain minimal set of assets, for example ['index.html', 'main.js'].
      • additional cache. Assets in this section are loaded after main section is successfully loaded. In ServiceWorker this section is loaded in activate event. If any of assets fails to download, then nothing is cached from the additional section and all the assets are moved to the optional section. If current update strategy is changed, then only failed to download assets are moved to the optional section, all other are successfully cached.
      • optional cache. This sections is only supported by ServiceWorker. As you may guess from its name, assets are cached only when they are fetched from the server. ServiceWorker won't download them ahead of time.
  • scope: string. Scope of the project, for example '/m/' or '/admin/'. Default: '/'.
  • updateStrategy: 'all' | 'hash' | 'changed'. Cache update strategy. Default: 'all'.
    • all strategy uses version passed to options as a cache tag. When version changes, old version cache is removed and new files are downloaded. Of course if files has same name were not changed (304 status returned), then probably browser won't download them again and will just update cache.
    • hash strategy is basically the same as all strategy, but uses webpack unique compilation hash as a tag.
    • changed strategy is more advanced than all or hash. To work properly it requires output assets to have unique names between compilations, e.g. file's unique hash in its name. With this strategy enabled, index.html file (or other files without dynamic name) should be placed in main section of the cache, otherwise they won't be revalidated.
      • For ServiceWorker this means that only new files will be downloaded and missing files deleted from the cache.
      • For AppCache it's basically same as previous strategies since AppCache revalidates all the assets. 304 HTTP status rule of course still works.
  • externals: Array<string>. Explicitly marks cache asset as external so you won't receive any warnings about it if asset it missing from webpack generated assets.
  • excludes: Array<string | globs_pattern>. Excludes selected assets from generation. Exclusion is applied before any assets is added to caches sections, hence global.
  • relativePaths: boolean. When set to true, all assets cache paths are generated relatively to ServiceWorker file or AppCache folder receptively. Setting scope to '' (empty string) sets this option to true and vice-versa. Default: false
  • version: string | Function. Version of the cache. Is used only with all update strategy. Might be a function, useful in watch-mode when you need dynamic date for each generation. Default: Current date.
  • rewrites: Function | Object. Rewrite function or rewrite map (Object). Useful when assets are server in a different way from the client perspective, e.g. usually index.html served as /. Default: function which rewrites /any/path/index.html to /any/path/.
  • ServiceWorker: Object | null | false. Settings for the ServiceWorker cache. Use null or false to disable ServiceWorker generation.
    • output: string. Relative (from the webpack's config output.path) output path for emitted script. Default: 'sw.js'.
    • entry: string. Relative or absolute path to file which will be used as ServiceWorker entry. Useful to implement additional function for it. Default: empty file.
  • AppCache: Object | null | false. Settings for the AppCache cache. Use null or false to disable AppCache generation.
    • NETWORK: string. Reflects AppCache's NETWORK section. Default: '*'.
    • directory: string. Relative (from the webpack's config output.path) output directly path for the AppCache files. Default: 'appcache/'.
    • caches: Array<string>. List of sections from caches option (main, additional or optional). Default: ['main', 'additional'].

Runtime

Besides plugin configuration, you also need to initialize it at runtime phase. This is most easier part:

require('offline-plugin/runtime').install();

Runtime install accepts 3 optional arguments: options, successCallback, errorCallback. options is not used at the moment (ignored), so it's better to just put null instead.

FAQ

Is it possible to minify ServiceWorker script output?
Yes, offline-plugin perfectly works with official webpack.optimize.UglifyJsPlugin, so if it's used your will get minified ServiceWorker script as well (no additional options required).

Is there a way to match assets with dynamic file names, like compilation hash or version?
Yes, it's possible with pattern matching, which is performed by minimatch library.
Example: main: ['index.html', 'scripts/main.*.js'].

Do I need to include cache-polyfill for the ServiceWorker?
No, it's included automatically for you.

License

MIT

CHANGELOG

2.0.0

  • Added relativePaths option. When true, all generated paths are relative to ServiceWorker file or AppCache folder. Useful in cases when app isn't in the root of domain, e.g. Github Pages. Setting scope to '' (empty string) is the same now as relativePaths: true.
  • Added excludes option to exclude assets from caches. Exclusion is global and is performed before any assets added to cache sections.
  • Not specified sections in caches now equals to empty selection. Previously, :rest: keyword was added automatically, now isn't.
  • ':rest:' keyword is now handled after all caches sections were handled. Previously it was handled immediately when found.
  • Plugin now throws an error when keyword :rest: is used more than once.
  • ServiceWorker generation now used Child Compilation instead weird hacks with entry injections.

1.3.1

Improved ServiceWorker entry generation: use compilation.namedChunks instead of compilation.assets to access service-entry and replace it. See NekR#10 for more details.

1.3

Added FALLBACK back section for AppCache and fixed generation of a NETWORK section.


More info in CHANGELOG

offline-plugin's People

Contributors

markdalgleish avatar nekr avatar stevenmathews avatar theultdev avatar

Watchers

 avatar  avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.