How to use jest-worker - 10 common examples

To help you get started, we’ve selected a few jest-worker 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 magento / baler / src / createMinifier.ts View on Github external
export function createMinifier() {
    trace('creating minification worker pool');
    const worker = (new Worker(require.resolve('./minifyWorker'), {
        forkOptions: {
            // surface console.log and friends in worker
            stdio: 'inherit',
        },
    }) as unknown) as typeof minifyWorker & InstanceType;

    return {
        minifyFromString: worker.minifyFromString,
        destroy: worker.end.bind(worker),
    };
}
github gridsome / gridsome / packages / plugin-critical / index.js View on Github external
api.afterBuild(async ({ queue, config }) => {
    const { outputDir: base, pathPrefix, publicPath } = config
    const patterns = options.paths.map(p => normalize(p))

    const pages = queue.filter(page => {
      return micromatch(page.path, patterns).length
    })

    const worker = new Worker(require.resolve('./lib/worker'))

    console.log(`Extract critical CSS (${pages.length} pages)`)

    await Promise.all(pages.map(async ({ htmlOutput }) => {
      try {
        await worker.generate(htmlOutput, {
          ignore: options.ignore,
          width: options.width,
          height: options.height,
          // TODO: remove pathPrefix fallback
          pathPrefix: publicPath || pathPrefix || '/',
          polyfill: options.polyfill,
          base
        })
      } catch (err) {
        worker.end()
github FormidableLabs / serverless-jetpack / index.js View on Github external
numLayers = layersPkgsToPackage.length;
      tasks = tasks.concat(layersPkgsToPackage.map((obj) => () =>
        this.packageLayer({ ...obj, worker, report })
      ));
    }

    // Run all packaging work.
    this._log(
      `Packaging ${numFns} functions, ${shouldPackageService ? 1 : 0} services, and `
      + `${numLayers} layers with concurrency ${concurrency}`
    );

    let results;
    if (concurrency > 1) {
      // Run concurrently.
      worker = new Worker(require.resolve("./util/bundle"), {
        numWorkers: concurrency
      });
      results = await Promise.all(tasks.map((fn) => fn()));
      worker.end();
    } else {
      // Run serially in-band.
      const limit = pLimit(1);
      results = await Promise.all(tasks.map(limit));
    }

    // Report.
    if (report) {
      this._report({ results });
    }

    return results;
github nrwl / nx / packages / web / src / utils / third-party / browser / action-executor.ts View on Github external
private ensureSmall(): JestWorker {
    if (this.smallWorker) {
      return this.smallWorker;
    }

    // small files are processed in a limited number of threads to improve speed
    // The limited number also prevents a large increase in memory usage for an otherwise short operation
    return (this.smallWorker = new JestWorker(workerFile, {
      exposedMethods: ['process'],
      setupArgs: [this.workerOptions],
      numWorkers: os.cpus().length < 2 ? 1 : 2,
      // Will automatically fallback to processes if not supported
      enableWorkerThreads: true
    }));
  }
github angular / angular-cli / packages / angular_devkit / build_angular / src / utils / action-executor.ts View on Github external
private ensureSmall(): JestWorker {
    if (this.smallWorker) {
      return this.smallWorker;
    }

    // small files are processed in a limited number of threads to improve speed
    // The limited number also prevents a large increase in memory usage for an otherwise short operation
    return (this.smallWorker = new JestWorker(workerFile, {
      exposedMethods: ['process', 'inlineLocales'],
      setupArgs: hasThreadSupport ? [this.workerOptions] : [[...serialize(this.workerOptions)]],
      numWorkers: os.cpus().length < 2 ? 1 : 2,
      enableWorkerThreads: hasThreadSupport,
    }));
  }
github angular / angular-cli / packages / angular_devkit / build_angular / src / utils / action-executor.ts View on Github external
private ensureLarge(): JestWorker {
    if (this.largeWorker) {
      return this.largeWorker;
    }

    // larger files are processed in a separate process to limit memory usage in the main process
    return (this.largeWorker = new JestWorker(workerFile, {
      exposedMethods: ['process', 'inlineLocales'],
      setupArgs: [[...serialize(this.workerOptions)]],
    }));
  }
github nrwl / nx / packages / web / src / utils / third-party / browser / action-executor.ts View on Github external
private ensureLarge(): JestWorker {
    if (this.largeWorker) {
      return this.largeWorker;
    }

    // larger files are processed in a separate process to limit memory usage in the main process
    return (this.largeWorker = new JestWorker(workerFile, {
      exposedMethods: ['process'],
      setupArgs: [this.workerOptions]
    }));
  }
github facebook / metro / packages / metro / src / DeltaBundler / WorkerFarm.js View on Github external
_makeFarm(
    workerPath: string,
    exposedMethods: $ReadOnlyArray,
    numWorkers: number,
  ) {
    const env = {
      ...process.env,
      // Force color to print syntax highlighted code frames.
      FORCE_COLOR: 1,
    };

    return new JestWorker(workerPath, {
      computeWorkerKey: this._config.stickyWorkers
        ? this._computeWorkerKey
        : undefined,
      exposedMethods,
      forkOptions: {env},
      numWorkers,
    });
  }
github zeit / next.js / packages / next / build / index.ts View on Github external
const buildManifestPath = path.join(distDir, BUILD_MANIFEST)

  const sprPages = new Set()
  const staticPages = new Set()
  const invalidPages = new Set()
  const hybridAmpPages = new Set()
  const additionalSprPaths = new Map>()
  const pageInfos = new Map()
  const pagesManifest = JSON.parse(await fsReadFile(manifestPath, 'utf8'))
  const buildManifest = JSON.parse(await fsReadFile(buildManifestPath, 'utf8'))

  let customAppGetInitialProps: boolean | undefined

  process.env.NEXT_PHASE = PHASE_PRODUCTION_BUILD

  const staticCheckWorkers = new Worker(staticCheckWorker, {
    numWorkers: config.experimental.cpus,
    enableWorkerThreads: config.experimental.workerThreads,
  })
  staticCheckWorkers.getStdout().pipe(process.stdout)
  staticCheckWorkers.getStderr().pipe(process.stderr)

  const analysisBegin = process.hrtime()
  await Promise.all(
    pageKeys.map(async page => {
      const actualPage = page === '/' ? '/index' : page
      const size = await getPageSizeInKb(
        actualPage,
        distDir,
        buildId,
        buildManifest,
        config.experimental.modern
github theKashey / devolution / src / index.js View on Github external
columnDefault: {
        width: 50
      },
      columns: {
        0: {
          width: 70,
        },
        1: {
          alignment: 'right'
        }
      },
      columnCount: 2
    });
    tableStream.write(['file', 'polyfills required']);

    const worker = new Worker(require.resolve('./workers/detect'));
    const polyfillsLeft = x => basePolyfills.indexOf(x) < 0;

    if (mainBundle && mainBundle !== '.') {
      basePolyfills = polyfills[mainBundle] = processPolyfills(
        await worker.extractPolyfills(dist, mainBundle, options.babelScan, definitions)
      );
      tableStream.write([mainBundle, basePolyfills.length]);
    }

    if (addPolyfills && !mainBundle) {
      throw new Error("devolution: in order to use `addPolyfills` define `rootBundles` condition.")
    }

    await Promise.all(
      jsFiles.map(async file => {
        if (file !== mainBundle) {

jest-worker

Module for executing heavy tasks under forked processes in parallel, by providing a `Promise` based interface, minimum overhead, and bound workers.

MIT
Latest version published 1 year ago

Package Health Score

88 / 100
Full package analysis

Popular jest-worker functions

Similar packages