Cloud Defense Logo

Products

Solutions

Company

Book A Live Demo

Top 10 Examples of "workbox-build in functional component" in JavaScript

Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'workbox-build' 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.

async function getWorkboxSWImport(compilation, config) {
  switch (config.importWorkboxFrom) {
    case 'cdn': {
      return [getModuleUrl('workbox-sw')];
    }

    case 'local': {
    // This will create a local copy of the Workbox runtime libraries in
    // the output directory, independent of the webpack build pipeline.
    // In general, this should work, but one thing to keep in mind is that
    // when using the webpack-dev-server, the output will be created on
    // disk, rather than in the in-memory filesystem. (webpack-dev-server will
    // still be able to serve the runtime libraries from disk.)
      const wbDir = await copyWorkboxLibraries(path.join(
          compilation.options.output.path, config.importsDirectory));

      // We need to set this extra option in the config to ensure that the
      // workbox library loader knows where to get the local libraries from.
      config.modulePathPrefix = (compilation.options.output.publicPath || '') +
        path.join(config.importsDirectory, wbDir).split(path.sep).join('/');

      const workboxSWImport = config.modulePathPrefix + '/workbox-sw.js';
      return [workboxSWImport];
    }

    case 'disabled': {
      return null;
    }

    default: {
async handleEmit(compilation, readFile) {
    const workboxSWImports = getWorkboxSWImports(compilation, this.config);
    let entries = getManifestEntriesFromCompilation(compilation, this.config);

    const sanitizedConfig = sanitizeConfig.forGetManifest(this.config);
    // If there are any "extra" config options remaining after we remove the
    // ones that are used natively by the plugin, then assume that they should
    // be passed on to workbox-build.getManifest() to generate extra entries.
    if (Object.keys(sanitizedConfig).length > 0) {
      // If globPatterns isn't explicitly set, then default to [], instead of
      // the workbox-build.getManifest() default.
      sanitizedConfig.globPatterns = sanitizedConfig.globPatterns || [];
      const {manifestEntries} = await getManifest(sanitizedConfig);
      entries = entries.concat(manifestEntries);
    }

    const manifestString = stringifyManifest(entries);
    const manifestAsset = convertStringToAsset(manifestString);
    const manifestHash = getAssetHash(manifestAsset);
    const manifestFilename = `precache-manifest.${manifestHash}.js`;
    compilation.assets[manifestFilename] = manifestAsset;
    this.config.importScripts.push(manifestFilename);

    // workboxSWImports might be null if importWorkboxFrom is 'disabled'.
    if (workboxSWImports) {
      // workboxSWImport is an array, so use concat() rather than push().
      this.config.importScripts = this.config.importScripts.concat(
        workboxSWImports);
    }
async function getWorkboxSWImport(compilation, config) {
  switch (config.importWorkboxFrom) {
    case 'cdn': {
      return [getModuleUrl('workbox-sw')];
    }

    case 'local': {
    // This will create a local copy of the Workbox runtime libraries in
    // the output directory, independent of the webpack build pipeline.
    // In general, this should work, but one thing to keep in mind is that
    // when using the webpack-dev-server, the output will be created on
    // disk, rather than in the in-memory filesystem. (webpack-dev-server will
    // still be able to serve the runtime libraries from disk.)
      const wbDir = await copyWorkboxLibraries(path.join(
          compilation.options.output.path, config.importsDirectory));

      // We need to set this extra option in the config to ensure that the
      // workbox library loader knows where to get the local libraries from.
      config.modulePathPrefix = (compilation.options.output.publicPath || '') +
        path.join(config.importsDirectory, wbDir).split(path.sep).join('/');
gulp.task('service-worker', () => {
    return workboxBuild.injectManifest({
        swSrc: path.join(__dirname, './public/src/js/sw.js'),
        swDest: path.join(__dirname, './sw.js'),
        globDirectory: path.join(__dirname, './'),

        // 注意:这里有个坑!后缀{js,css,xxx} 逗号之间不能加空格,否则识别有问题!!!
        globPatterns: [
            'public/**/*.{js,css,html,png,jpg,svg,ico,swf}',
            // 'node_modules/bootstrap/**/*.min.{js,css}',
            // 'node_modules/@fortawesome/**/*.{min.css,eot,ttf,woff,woff2}',
            // 'node_modules/blueimp-file-upload/**/*.{js,css}',
            // 'node_modules/sweetalert/dist/**/*.{js,css}',
            // 'node_modules/jquery/dist/**/*.{js,css}',
            // 'node_modules/metismenu/dist/**/*.{js,css}',
            // 'node_modules/lodash/**/*.min.js',
            // 'node_modules/fuelux/dist/**/*.{js,css}',
            // 'node_modules/simplemde/dist/**/*.{js,css}',
assert(Array.isArray(params.input), errors['missing-input']);

  // Default to showing the help message if there's no command provided.
  const [command = 'help', option] = params.input;

  switch (command) {
    case 'wizard': {
      await runWizard(params.flags);
      break;
    }

    case 'copyLibraries': {
      assert(option, errors['missing-dest-dir-param']);
      const parentDirectory = upath.resolve(process.cwd(), option);

      const dirName = await workboxBuild.copyWorkboxLibraries(parentDirectory);
      const fullPath = upath.join(parentDirectory, dirName);

      logger.log(`The Workbox libraries were copied to ${fullPath}`);
      logger.log(ol`Add a call to workbox.setConfig({modulePathPrefix: '...'})
        to your service worker to use these local libraries.`);
      logger.log(`See https://goo.gl/Fo9gPX for further documentation.`);
      break;
    }

    case 'generateSW':
    case 'injectManifest': {
      const configPath = upath.resolve(process.cwd(),
          option || constants.defaultConfigFile);

      let config;
      try {
join(globals.rootDir, src),
                            join(build.path, dest),
                            options
                        );
                    }
                ));
            }
        }
        // SPA build process
        else {
            await webpackCompile(await this.createSPAConfig(), build.stats);
        }

        if (serviceWorker.enable !== false) {
            // Copy workbox files to dist/static/workbox-v3.*.*/
            await copyWorkboxLibraries(join(build.path, ASSETS_DIRNAME_IN_DIST));
        }
    }
}
async function getWorkboxSWImport(compilation, config) {
  switch (config.importWorkboxFrom) {
    case 'cdn': {
      return [getModuleUrl('workbox-sw')];
    }

    case 'local': {
      // This will create a local copy of the Workbox runtime libraries in
      // the output directory, independent of the webpack build pipeline.
      // In general, this should work, but one thing to keep in mind is that
      // when using the webpack-dev-server, the output will be created on
      // disk, rather than in the in-memory filesystem. (webpack-dev-server will
      // still be able to serve the runtime libraries from disk.)
      const wbDir = await copyWorkboxLibraries(compilation.options.output.path);
      const workboxSWImport = (compilation.options.output.publicPath || '')
        + wbDir + '/workbox-sw.js';
      // We need to set this extra option in the config to ensure that the
      // workbox library loader knows where to get the local libraries from.
      config.modulePathPrefix = wbDir;
      return [workboxSWImport];
    }

    case 'disabled': {
      return null;
    }

    default: {
      // If importWorkboxFrom is anything else, then treat it as the name of
      // a webpack chunk that corresponds to the custom compilation of the
      // Workbox code.
async function buildWorker() {
  let app = {
    buildId: fs.readFileSync(`${dotNext}/BUILD_ID`, 'utf8'),
    precaches: []
  }

  const stats = await loadJsonFile(`${dotNext}/build-stats.json`);
  Object.keys(stats).map(src => {
    // /_next/9265fa769281943ee96625770433e573/app.js
    app.precaches.push(`/_next/${stats[src].hash}/${src}`)
  })

  app = await addChunks(app);
  app = await addBundles(app);

  const workboxSrc = await workbox.copyWorkboxLibraries(dotNext);

  fs.writeFileSync(
    target,
    swSnippet(
      JSON.stringify(app.precaches, null, 2),
      workboxSrc,
    ),
    'utf8'
  );
}
` InjectManifest. Please use 'cdn' or a chunk name instead.`);
    }

    const workboxSWImports = await getWorkboxSWImports(
      compilation, this.config);
    let entries = getManifestEntriesFromCompilation(compilation, this.config);

    const sanitizedConfig = sanitizeConfig.forGetManifest(this.config);
    // If there are any "extra" config options remaining after we remove the
    // ones that are used natively by the plugin, then assume that they should
    // be passed on to workbox-build.getManifest() to generate extra entries.
    if (Object.keys(sanitizedConfig).length > 0) {
      // If globPatterns isn't explicitly set, then default to [], instead of
      // the workbox-build.getManifest() default.
      sanitizedConfig.globPatterns = sanitizedConfig.globPatterns || [];
      const {manifestEntries} = await getManifest(sanitizedConfig);
      entries = entries.concat(manifestEntries);
    }

    const manifestString = stringifyManifest(entries);
    const manifestAsset = convertStringToAsset(manifestString);
    const manifestHash = getAssetHash(manifestAsset);
    let manifestFilename = `precache-manifest.${manifestHash}.js`;
    if (this.config.manifestFilename) {
        manifestFilename = this.config.manifestFilename.replace('[manifest]', manifestFilename);
    }

    compilation.assets[manifestFilename] = manifestAsset;
    compilation.assets['static/js/' + manifestFilename] = manifestAsset;

    this.config.importScripts.push(
      (compilation.options.output.publicPath || '') + manifestFilename);
compilation.assets[manifestFilename] = manifestAsset;
    this.config.importScripts.push(
      (compilation.options.output.publicPath || '') + manifestFilename);

    // workboxSWImports might be null if importWorkboxFrom is 'disabled'.
    if (workboxSWImports) {
      // workboxSWImport is an array, so use concat() rather than push().
      this.config.importScripts = this.config.importScripts.concat(
        workboxSWImports);
    }

    const sanitizedConfig = sanitizeConfig.forGenerateSWString(this.config);
    // If globPatterns isn't explicitly set, then default to [], instead of
    // the workbox-build.generateSWString() default.
    sanitizedConfig.globPatterns = sanitizedConfig.globPatterns || [];
    const serviceWorker = await generateSWString(sanitizedConfig);
    compilation.assets[this.config.swDest] =
      convertStringToAsset(serviceWorker);
  }

Is your System Free of Underlying Vulnerabilities?
Find Out Now