Code Monkey home page Code Monkey logo

offline-plugin's Introduction

offline-plugin logo

offline-plugin for webpack

backers sponsors npm npm


This plugin is intended to provide an 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 become offline ready by caching all (or some) of the webpack output assets.

Sponsors

Become a sponsor and get your logo on our README on Github with a link to your site.
Become a sponsor

Install

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

Setup

First, instantiate the plugin in your webpack.config:

// webpack.config.js example

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

module.exports = {
  // ...

  plugins: [
    // ... other plugins
    // it's always better if OfflinePlugin is the last plugin added
    new OfflinePlugin()
  ]
  // ...
}

(and optionally configure with options)

Then, add the runtime into your entry file (typically main entry):

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

ES6/Babel/TypeScript

import * as OfflinePluginRuntime from 'offline-plugin/runtime';
OfflinePluginRuntime.install();

For more details of usage with TypeScript see here

offline-plugin isn't working?

โ„น๏ธ Troubleshooting | FAQ

Docs

Examples

Articles

Options

All options are optional and offline-plugin can be used without specifying them.

Who is using offline-plugin

Projects

PWAs

If you are using offline-plugin, feel free to submit a PR to add your project to this list.

Like offline-plugin?

Support it by giving feedback, contributing, becoming a backer/sponsor or just by ๐ŸŒŸ starring the project!

Backers

Support us with a monthly donation and help us continue our activities. [Become a backer]

Contribution

See CONTRIBUTING

License

MIT
Logo

CHANGELOG

CHANGELOG

offline-plugin's People

Contributors

1pete avatar amiuhle avatar ctrlplusb avatar diwakar-s-maurya avatar domderen avatar egoist avatar fengzilong avatar ggalansmithee avatar gitter-badger avatar lcxfs1991 avatar markdalgleish avatar martinvd avatar mojoaxel avatar moox avatar mstange avatar mxstbr avatar nekr avatar posva avatar sarmadsangi avatar seveves avatar simon04 avatar st-ex avatar stevenmathews avatar theultdev avatar thmsobrmlr avatar thomaswelton avatar tsnieman avatar whosford avatar xdamman avatar zouhir avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

offline-plugin's Issues

Dev mode

  • Allow offline-plugin to disable booth tools (ServiceWorker, AppCache) so no files are generated at dev mode.
  • Allow offline-plugin/runtime to be used (does nothing) even when offline-plugin is not used

Explicitly mark external assets

Add a way to explicitly mark external assets so no warnings are reported into console. Something like this should work:

{
  ...
  externals: [
    'index.html'
  ],
  ...
}

Path to appcache/sw.js

I am probably missing something but I can't get to find how to configure the path to the appcache directory and sw.js file.

I have an express application serving assets at /assets so the current structure looks like:

/assets
  /appcache
    /manifest.appcache
    /manifest.html
  /js
    /app.js
    /sw.js

The problem is that the runtime installation tries to fetch the manifest from /appcache/manifest.html instead of /assets/appcache/manifest.html. I tried to play around with publicPath but didn't see any effects, same for relativePaths. I tried to pass options to the runtime function but after digging the code, seems like it's completely ignored.

Is there a way to configure the appcache and sw.js path? Must it be located at the root?

Always fetch index.html and only serve cached version when offline

Currently I place index.html to main assets and it is an external file. When I update it, because service worker script always serve it from the cache so the client will not see the new version.

I think we need an option to specify entry files and always fetch them while online. Only serve the cached version if the fetch failed.

Custom template or extension point?

Hi! Thank you for this plugin, really useful and works well.

I would like to hook into the service worker code (I'd like to have custom logic in the fetch listener), and I was wondering if there was any way to hook into it right now?

Thanks,
William

Runtime caches

Hello, really nice plugin!

I'm doing a server side render of blog posts and was hoping to cache the server side render as externals, but your documentation says I cannot pattern match externals. What would be the recommended solution here? I'm really trying to avoid having to list each possible blog post path as an external.

    new OfflinePlugin({
      caches: {
        main: [
          '/',
          ':rest:',
        ],
        additional: [
          '/post/*',
        ],
      },
      externals: [ '/', '/post/*' ],
      scope: '/',
      updateStrategy: 'all',
      version: 'v1',
      ServiceWorker: {
        output: 'sw.js',
      },
      AppCache: {
        directory: 'appcache/',
      },
    }),```

Tests

Would be good if someone could contribute tests to this project, they are at least good to have and unfortunately I do not think that I will have for both: implementation and tests.

Implement caches maps

The idea is serve one cache for any navigation request, /albums for example. Same, if cache is empty, any navigation request should populate given cache.

Probably not any. Maybe something specified in map like this:

{
  '/albums': '/',
  '/gallery': '/'
}
// or
{
  '/*': '/shell.html'
}

Here is the use case number one: #27
Second use case it to serve server-rendered content on network requests, but in ServiceWorker, cache the AppShell.

[meta] Roadmap v3

Overview

v3 is going to fix most import issues in this plugin and here is what was done so far: CHANGELOG

What is planned

  • Update and reformat README to match latest changes (in progress)
  • Store assets-hashed in ServiceWorker and always use updateStrategy: 'changed' to download only changed assets, even with different name (existed assets are renamed if needed). Issue #6
  • Runtime URLs/externals matching. Right now one can use sw-toolbox to do this (include it in SW's entry), but I want this to be fully declarative to be able to generate code for other targets, e.g. Java/Swift code for Cordova. Issue 26 (not for a v3 anymore)
  • Concider make additional cache not fail on individual errors
  • Test SW generation with source-maps Issue 42
  • Check fetched file's hash before caching Issue 43 Invalid.
  • Add basic lifetime events for AppCache Issue 44

This is most important things planned for v3. Other things may be added later, but is the roadmap at a moment.

respect publicPath

It would be great if this plugin respected the publicPath setting in output. Currently the service worker and manifest directory needs to be published at / which sometimes is not possible, for example on gh-pages.

Support for serviceWorker events

SW has some events like install , activated , but there is also special events like push and sync, keep these events in the config so that generate sw.js file will have this like

new OfflinePlugin({
            AppCache: false,
            caches: 'all',
            scope: '',
            relativePaths: true,
            updateStrategy: 'hash',
            events:{
                push:function(){
                   // Developer choice
                }
            }
        }),

Or any much better way it is okay.

Serivce worker failed to install

I just added the plugin to webpack config with the below configuration,

  new OfflinePlugin({
            AppCache: false,
            caches: 'all',
            scope: '/',
            relativePaths: true,
            updateStrategy: 'hash'
        }),

but it is only firing the install event but not the actiavte event, so i debugged in the chrome://serviceworker-internals/ , there i found this line
Error: {"columnNumber":-1,"lineNumber":-1,"message":"ServiceWorker failed to install","sourceURL":""} but this error is telling that it is failed, but why?

files are listing with out the hash tag

Actually for cache busting im using the webpack hash tag for every generate entry point. but the generate sw doeesnt have the hastag i.e., when my webpack generate file is main.js?78787827878 but sw listed it as only main.js this should be problematic when second time loading the site.

Multiple webpack entry points

My webpack build currently creates several separate single page apps by defining multiple entry points.

It doesn't seem possible to separate the caches this plugin creates into one per each webpack entry point. Is this not supported?

Suggest add a uninstall function

The code that I used to uninstall sw

  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.getRegistrations().then(registrations => {
      for (const registration of registrations) {
        registration.unregister()
      }
    })
    caches.keys().then(keyList => {
      return Promise.all(keyList.map(key => {
        return caches.delete(key)
      }))
    })
  }

Allow hashing the filename of sw.js

We are caching all assets with a far-future expire on our webserver. Therefore we need to hash the service worker script in order to update to new versions, but this does not seem to work:

new OfflinePlugin({
  ServiceWorker: {
    output: 'sw-[hash].js'
  }
})

Just outputs it literal: sw-[hash].js

Runtime doesn't really seem to do anything

Hi, I'm not sure if this is a bug, but it looks like one... I'm using

"offline-plugin": "^2.1.0",

I added the following code:

let runtime = require('offline-plugin/runtime');
console.log('Runtime', runtime.install.toString());

And got the following output, in Firefox Developer Edition 47.0a2 and regular Firefox:

Runtime function () {}

In other words: the install function doesn't seem to do anything. I'm not sure if I'm doing something wrong or whether it's a bug. I've added the plugin without any options, as they were said to be optional:

new OfflinePlugin()

(And if relevant: my code, although without the debugging statements, is located at Gitlab.)

External URLs are prefixed with relative path

If I add external resources for caching, they are prefixed with ./ like this:

  "assets": {
    "main": [
      "./"
    ],
    "additional": [],
    "optional": [
      "./https://weblibrary.myserver.com/styles/main.css",
      "./https://weblibrary.myserver.com/fonts/icons.woff"
    ]
  },

I can set relativePaths: false, but I don't really see why you can't have both relative paths and a few external URLs. Should be easy to detect?

Support cache of absolute urls

Need add support of cache absolute (and CORS) url, e.g.

new OfflinePlugin({
  caches: {
    main: ['index.html', 'https://fonts.googleapis.com/css?family=Roboto:400,500,900'],
    additional: [':rest:']
  }
})

Of course, relativePaths and scope should be ignored for absolute urls.

OfflinePlugin: ServiceWorker entry has more than one output file, only first will be used

I'm using webpack dev server, and to use inline mode I need to include the dev server entry in my webpack configuration.

var config = require("./webpack.config.js");
config.entry.app.unshift("webpack-dev-server/client?http://localhost:8080");
var compiler = webpack(config);
var server = new webpackDevServer(compiler, {...});
server.listen(8080);

This effectively leaves my webpack with:

{
    entry: {
        app: [
            "webpack-dev-server/client?http://localhost:8080",
            "./app.js" 
        ]
    }

With the warning that OfflinePlugin produces, I can't figure out what problem it causes or what I can do to get rid of the warning other than just not use Webpack's dev server (not an option).

"network" option for all

Current NETWORK option is present only for AppCache and reflects NETWORK section of it.
Need to make make network option global and implement request filtering in ServiceWorker runtime.

SW cache name

Add a way to change SW cache name. Currently it's always webpack-offline.

Notifying users of new content

I currently set offline-plugin's version option to the version of my package.json, so that it automatically changes when I deploy a new version.

For AppCache, this results in a changed manifest file, which will download the new files and fire an updateready event. I can then tell the user that there is new content available and refresh the page.

For ServiceWorker though, changing the version results in a new Cache being used. The current SW will still be active and use the old cache, and the new SW will only become active when the user closes and reopens the tab/window.

Is there a way to notify the user of the changes and force switching to the new SW? Or could the old SW somehow pick up the new cache available?

Or am I doing something completely wrong and this should just work? Right now I can refresh the Browser all day, unless I close the tab the SW will always give me the old, cached content...

Use IndexedDB to store assets hashes

To allow changed update strategy to be used with any files names (even without changing them on file update) ServiceWorker should know current hash (easy, just generated map) and old hash (hard, need to store somehow on the client) of the file.

Storing custom headers in request does not work (Headers are immutable). IndexedDB should work.

bundle.js not found

If I add OfflinePlugin as same as setup in README.md. I would get Failed to load resource: the server responded with a status of 404 (Not Found). How could I solve this problem?

regex for 'excludes' option?

Hi, great plugin! love it!

just curious about how to use regex for excludes option?

for example, i have list of touch icons and favicon, they all put in 'icons-randomHashNumber' folder, how can I exclude this folder?

plz advise, thx!

Port to Browserify

I personally do not use Browserify, but if people need it, then I can do the port.

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.