thread-loader

免责声明 thread-loader是一个由社区成员维护的第三方包,它可能不具备与 webpack 相同的支持、安全策略或许可证,并且不受 webpack 维护。

npm node tests coverage discussion size

在工作池中运行指定的加载器。

入门

npm install --save-dev thread-loader

yarn add -D thread-loader

pnpm add -D thread-loader

将此加载器置于其他加载器之前。以下加载器将在工作池中运行。

在工作池中运行的加载器有其限制。例如

  • 加载器不能发出文件。
  • 加载器不能使用自定义加载器 API (即通过插件)。
  • 加载器不能访问 webpack 选项。

每个工作进程都是一个独立的 Node.js 进程,其开销约为 600 毫秒。此外,进程间通信也会带来额外的开销。

仅将此加载器用于开销大的操作!

示例

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        include: path.resolve('src'),
        use: [
          'thread-loader',
          // your expensive loader (e.g babel-loader)
        ],
      },
    ],
  },
};

带选项

use: [
  {
    loader: 'thread-loader',
    // loaders with equal options will share worker pools
    options: {
      // the number of spawned workers, defaults to (number of cpus - 1) or
      // fallback to 1 when require('os').cpus() is undefined
      workers: 2,

      // number of jobs a worker processes in parallel
      // defaults to 20
      workerParallelJobs: 50,

      // additional node.js arguments
      workerNodeArgs: ['--max-old-space-size=1024'],

      // Allow to respawn a dead worker pool
      // respawning slows down the entire compilation
      // and should be set to false for development
      poolRespawn: false,

      // timeout for killing the worker processes when idle
      // defaults to 500 (ms)
      // can be set to Infinity for watching builds to keep workers alive
      poolTimeout: 2000,

      // number of jobs the pool distributes to the workers
      // defaults to 200
      // decrease for less efficient but more fair distribution
      poolParallelJobs: 50,

      // name of the pool
      // can be used to create different pools with otherwise identical options
      name: 'my-pool',
    },
  },
  // your expensive loader (e.g babel-loader)
];

预热

为了避免启动工作进程时的高延迟,可以预热工作池。

这将启动池中最大数量的工作进程,并将指定的模块加载到 Node.js 模块缓存中。

const threadLoader = require('thread-loader');

threadLoader.warmup(
  {
    // pool options, like passed to loader options
    // must match loader options to boot the correct pool
  },
  [
    // modules to load
    // can be any module, i.e.
    'babel-loader',
    '@babel/preset-env',
    'sass-loader',
  ],
);

贡献

我们欢迎所有贡献!如果您是新用户,请在提交问题或拉取请求之前花一些时间阅读我们的贡献指南。

贡献

许可证

MIT