Cloud Defense Logo

Products

Solutions

Company

Book A Live Demo

Top 10 Examples of "sw-precache in functional component" in JavaScript

Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'sw-precache' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.

}

// 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.');
});
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 '/'.
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
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"
                },
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
	);
});
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)
}
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);
}
'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);
    }
});
function writeServiceWorkerFile(rootDir, handleFetch) {
    swPrecache.write(path.join(rootDir, 'service-worker.js'), {
        handleFetch: handleFetch,
        staticFileGlobs: getAssets(rootDir),
        stripPrefix: rootDir + '/'
    });
}
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']);

Is your System Free of Underlying Vulnerabilities?
Find Out Now