块编辑器开发文档

@wordpress/worker-threads

💡 云策文档标注

概述

@wordpress/worker-threads 是一个用于在 WordPress 开发中实现类型安全的 Web Worker 通信的实用工具包,基于 RPC(远程过程调用)机制。它简化了主线程与 Web Worker 之间的交互,提供自动化的 Promise 处理、可传输对象检测和完整的 TypeScript 支持。

关键要点

  • 提供基于 Promise 的异步方法调用,使 Web Worker 通信更易于管理。
  • 自动检测和传输可转移对象(如 ArrayBuffer),实现零拷贝性能优化。
  • 支持完整的 TypeScript 类型安全,包括方法签名推断和错误传播。
  • 通过 wrap() 和 expose() 函数简化主线程和 Worker 线程的 API 封装。
  • 包含错误处理机制,确保 Worker 中的错误能正确传递到主线程。

代码示例

// Worker 线程示例 (worker.ts)
import { expose } from '@wordpress/worker-threads/worker';

const api = {
    async processImage( buffer: ArrayBuffer, quality: number ): Promise<ArrayBuffer> {
        // 图像处理逻辑
        return resultBuffer;
    },
    async calculateSum( a: number, b: number ): Promise<number> {
        return a + b;
    },
};

expose( api );

// 主线程示例 (main.ts)
import { wrap, terminate } from '@wordpress/worker-threads';
import type { WorkerAPI } from './worker';

const worker = new Worker( new URL( './worker.js', import.meta.url ), {
    type: 'module',
} );

const api = wrap<WorkerAPI>( worker );
const result = await api.processImage( imageBuffer, 0.82 );
const sum = await api.calculateSum( 1, 2 );
terminate( api );

注意事项

  • 使用 wrap() 函数时需确保传入正确的 Worker 实例和类型定义,以保持类型安全。
  • 在 Worker 线程中,expose() 应仅调用一次,以避免重复暴露 API。
  • 终止 Worker 时使用 terminate() 函数,以清理资源并拒绝待处理的调用。
  • 该包是 Gutenberg 项目的一部分,贡献者需遵循项目的贡献指南。

📄 原文内容

Utilities for type-safe Web Worker communication with RPC (Remote Procedure Call).

This package provides a simple and efficient way to communicate between the main thread and Web Workers, automatically handling:

  • Promise-based async method calls
  • Automatic transferable detection (ArrayBuffer, etc.)
  • Type-safe API with full TypeScript support
  • Error propagation from worker to main thread

Installation

Install the module:

npm install @wordpress/worker-threads

Usage

Worker Thread

Create a worker file that exposes methods to the main thread:

// worker.ts
import { expose } from '@wordpress/worker-threads/worker';

const api = {
    async processImage( buffer: ArrayBuffer, quality: number ): Promise<ArrayBuffer> {
        // ... image processing logic
        return resultBuffer;
    },

    async calculateSum( a: number, b: number ): Promise<number> {
        return a + b;
    },
};

expose( api );

// Export the type for use with wrap() on the main thread
export type WorkerAPI = typeof api;

Main Thread

Wrap the worker to get a type-safe proxy:

// main.ts
import { wrap, terminate } from '@wordpress/worker-threads';
import type { WorkerAPI } from './worker';

// Create the worker
const worker = new Worker( new URL( './worker.js', import.meta.url ), {
    type: 'module',
} );

// Wrap it to get the RPC proxy
const api = wrap<WorkerAPI>( worker );

// Call methods as async functions
const result = await api.processImage( imageBuffer, 0.82 );
const sum = await api.calculateSum( 1, 2 );

// Clean up when done
terminate( api );

API Reference

Main Thread API

wrap<T>( worker: Worker ): Remote<T>

Wraps a Worker to provide a type-safe RPC interface. The returned proxy object allows calling methods on the worker as if they were local async functions.

terminate( remote: Remote<unknown> ): void

Terminates a wrapped worker and cleans up resources. Any pending calls will be rejected.

Worker Thread API

expose<T>( target: T ): void

Exposes an object’s methods to be called from the main thread. Should be called once in the worker script.

Types

Remote<T>

A type that converts all methods of T to their async versions. Each method returns Promise<Awaited<ReturnType>>.

Features

Automatic Transferable Detection

The package automatically detects and transfers ArrayBuffer and other transferable objects, providing zero-copy performance for large data:

// ArrayBuffers are automatically transferred, not copied
const result = await api.processImage( largeImageBuffer );

Error Handling

Errors thrown in the worker are properly propagated to the main thread:

try {
    await api.riskyOperation();
} catch ( error ) {
    console.error( 'Worker error:', error.message );
}

TypeScript Support

Full type inference for method signatures:

// TypeScript knows the return type and parameter types
const result: ArrayBuffer = await api.processImage( buffer, 0.82 );

Contributing to this package

This is an individual package that’s part of the Gutenberg project. The project is organized as a monorepo. It’s made up of multiple self-contained software packages, each with a specific purpose. The packages in this monorepo are published to npm and used by WordPress as well as other software projects.

To find out more about contributing to this package or Gutenberg as a whole, please read the project’s main contributor guide.