How to use sw-precache - 10 common examples

To help you get started, we’ve selected a few sw-precache examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github google / indexable-pwa-samples / routes / all.js View on Github external
}

// Google Site Verification is necessary for some Google tools such as
// Search Console. For convenience this is configurable.
if ('GOOGLE_SITE_VERIFICATION_TOKEN' in process.env) {
  serverConfig.googleSiteVerificationToken =
      process.env.GOOGLE_SITE_VERIFICATION_TOKEN;
}

console.log('Server Configuration:', serverConfig);

// Based on the render mode we use a different sw-precache configuration file
// to generate the Service Worker.
var swPrecacheConfig = require('./../sw-precache-config-' +
    serverConfig.renderMode + '.js');
swPrecache.write(path.join(__dirname,
    '/../public/generated-service-worker.js'), swPrecacheConfig,
    function(err) {
  if (err) console.log(err);
});

// Cache the CSS in memory to embed into AMP documents where necessary:
var globalCSS = '';

fs.readFile(path.join(__dirname, '/../public/stylesheets/style.css'),
    function(err, data) {
  if (err) console.log(err);

  globalCSS = data;
  console.log('CSS preloaded for AMP requests.');
});
github borablanca / orgmodeweb / gulpfile.babel.js View on Github external
gulp.task("generate-service-worker", gulp.series("copy-sw-scripts", () => {
  const rootDir = "dist";
  const filepath = path.join(rootDir, "service-worker.js");

  return swPrecache.write(filepath, {
    // Used to avoid cache conflicts when serving on localhost.
    cacheId: pkg.name || "orgmodeweb",
    // sw-toolbox.js needs to be listed first. It sets up methods used in runtime-caching.js.
    importScripts: [
      "js/sw/sw-toolbox.js",
      "js/sw/runtime-caching.js"
    ],
    staticFileGlobs: [
      `${rootDir}/img/**/*`,
      `${rootDir}/js/**/*.js`,
      `${rootDir}/css/**/*.css`,
      `${rootDir}/*.{html,json}`
    ],
    // Translates a static file path to the relative URL that it's served from.
    // This is '/' rather than path.sep because the paths returned from
    // glob always use '/'.
github bunq / doc / generate-service-worker.js View on Github external
var swPrecache = require("sw-precache");
var rootDir = "docs";

swPrecache.write(rootDir + "/service-worker.js", {
    /**
     * Cache the index file statically
     * Re-run this script to update the file hash and trigger an update for all clients
     */
    staticFileGlobs: [rootDir + "/index.html"],
    // increase max pre-cache size
    maximumFileSizeToCacheInBytes: 30971520,
    // remove "docs" from the static file path
    stripPrefix: rootDir,
    // runtimeCaching which matches patterns and applices the specific handlers
    runtimeCaching: [
        {
            urlPattern: /swagger\.json$/,
            /**
             * Return cached version first when possible but always attempt to update in the background
             * @see https://github.com/GoogleChromeLabs/sw-toolbox/blob/master/docs/api.md#toolboxfastest
github DennisSnijder / BunqWeb / resources / webpack / SWHelper.js View on Github external
const SWHelper = (fileList = false, options = { publicDir: "web" }) => {
    let staticFiles = [];

    if (PRODUCTION) {
        if (fileList) {
            // merge the afterEmitFiles list and remove duplicates
            staticFiles = staticFiles.concat(fileList);
        } else {
            // do a glob on the dist folder for webpack output files
            staticFiles = staticFiles.concat(glob.sync("/assets/dist/*"));
        }
    }

    // write the precache file
    swPrecache.write(
        options.publicDir + "/sw.js",
        {
            staticFileGlobs: staticFiles,
            stripPrefix: options.publicDir,
            // runtimeCaching which matches patterns and applies the specific handlers
            runtimeCaching: [
                {
                    // cache api attachements in production mode
                    urlPattern: /\/api\/attachment\/[.]*/,
                    handler: DEVELOPMENT ? "networkFirst" : "cacheFirst"
                },
                {
                    // dont cache api requests
                    urlPattern: /\/api/,
                    handler: "networkOnly"
                },
github ZenUml / web-sequence / gulpfile.js View on Github external
gulp.task('generate-service-worker', function (callback) {
	var swPrecache = require('sw-precache');
	var rootDir = 'app';

	swPrecache.write(
		`${rootDir}/service-worker.js`,
		{
			staticFileGlobs: [
				rootDir + '/**/*.{js,html,css,png,jpg,gif,svg,eot,ttf,woff}'
			],
			stripPrefix: `${rootDir}/`,

			// has to be increased to around 2.8mb for sass.worker.js
			maximumFileSizeToCacheInBytes: 2900000
		},
		callback
	);
});
github zhukov / webogram / gulpfile.js View on Github external
function writeServiceWorkerFile (rootDir, handleFetch, callback) {
  var config = {
    cacheId: packageJson.name,
    handleFetch: handleFetch,
    logger: $.util.log,
    staticFileGlobs: fileGlobs,
    stripPrefix: './' + rootDir + '/',
    importScripts: ['js/lib/push_worker.js'],
    verbose: true,
    maximumFileSizeToCacheInBytes: 3004152, // about 3MB, default is "2097152" 2MB,
    navigateFallback: 'index.html'
  }
  swPrecache.write(path.join(rootDir, 'service_worker.js'), config, callback)
}
github manshar / manshar / web-client / gulp / tasks / production / sw-precache.js View on Github external
importScripts: config[target].importScripts,
    navigateFallback: '/index.html',
    navigateFallbackWhitelist: routes.appRoutesRegexes,
    // If handleFetch is false (i.e. because this is called from swPrecache:dev), then
    // the service worker will precache resources but won't actually serve them.
    // This allows you to test precaching behavior without worry about the cache preventing your
    // local changes from being picked up during the development cycle.
    handleFetch: config[target].handleFetch,
    staticFileGlobs: config[target].staticFileGlobs,
    stripPrefix: config[target].stripPrefix,
    remoteResources: config[target].remoteResources,
    // verbose defaults to false, but for the purposes of this demo, log more.
    verbose: config[target].verbose
  };

  swPrecache.write(path.join(
      config[target].dest, 'service-worker.js'), precacheConfig, callback);
}
github GeekyAndFun / PWA-workshop / sw-precache-config.js View on Github external
'index.html',
        'common.js',
        'appConfig.js',
        'public/images/icon.png',
        'public/images/icon--flipped.png',
        'public/style.css',
        'public/main.js',
        'public/scripts/app.js',
        'public/scripts/messaging-service.js',
        'public/scripts/pre-data-ui.js',
        'public/scripts/ui.js',
    ],
    skipWaiting: true
};

swPrecache.write('./caching-service-worker.js', options, err => {
    if (err) {
        console.error(err);
    }
});
github Minishlink / pwa-qr-code-scanner / Gulpfile.js View on Github external
function writeServiceWorkerFile(rootDir, handleFetch) {
    swPrecache.write(path.join(rootDir, 'service-worker.js'), {
        handleFetch: handleFetch,
        staticFileGlobs: getAssets(rootDir),
        stripPrefix: rootDir + '/'
    });
}
github jadjoubran / laravel5-angular-material-starter / tasks / swPrecache.task.js View on Github external
new Task('generate-service-worker', function() {

        /*
          always read the latest config. Allows changing
          precache-config.json without reloading gulp
        */
        delete require.cache[require.resolve('./../precache-config.json')]
        var preCacheConfig = require('./../precache-config.json');

        return swPrecache.write(path.join('public', 'service-worker.js'), preCacheConfig);

    }).watch(['public/build/rev-manifest.json', 'precache-config.json']);

sw-precache

Generates a service worker to cache your local App Shell resources.

Apache-2.0
Latest version published 6 years ago

Package Health Score

50 / 100
Full package analysis

Popular sw-precache functions