Skip to content

Commit

Permalink
docs: add guide for using Web Workers (#3795)
Browse files Browse the repository at this point in the history
Co-authored-by: neverland <[email protected]>
  • Loading branch information
9aoy and chenjiahan authored Oct 23, 2024
1 parent 8d97f2a commit d9acb8e
Show file tree
Hide file tree
Showing 6 changed files with 144 additions and 8 deletions.
6 changes: 2 additions & 4 deletions website/docs/en/config/output/target.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -76,10 +76,6 @@ When `target` is set to `'node'`, Rsbuild will:

Refers to the build target running in the [Web Worker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) environment.

:::tip Web Worker
A web worker is a type of JavaScript program that runs in the background, independently of other scripts, without affecting the performance of the page. This makes it possible to run long-running scripts, such as ones that handle complex calculations or access remote resources, without blocking the user interface or other scripts. Web workers provide an easy way to run tasks in the background and improve the overall performance of web applications.
:::

When `target` is set to `'web-worker'`, Rsbuild will:

- Set Rspack's [target](https://rspack.dev/config/target) to `'webworker'`.
Expand All @@ -88,6 +84,8 @@ When `target` is set to `'web-worker'`, Rsbuild will:
- The default code split strategy will be disabled, and **dynamic import can not work**, because the Web Worker only runs a single JavaScript file.
- Disable the HMR.

For more information, please refer to: [Using Web Workers](/guide/basic/web-workers).

## Other targets

[Rspack](https://rspack.dev/config/target) supports other target types, such as `electron-main` and `electron-renderer`.
Expand Down
1 change: 1 addition & 0 deletions website/docs/en/guide/basic/_meta.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"typescript",
"tailwindcss",
"unocss",
"web-workers",
"static-deploy",
"upgrade-rsbuild"
]
69 changes: 69 additions & 0 deletions website/docs/en/guide/basic/web-workers.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# Use Web Workers

This chapter introduces how to configure and use [Web Workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers) in Rsbuild project.

:::tip Web Workers
Web Workers are a type of JavaScript program that runs in the background, independently of other scripts, without affecting the performance of the page. This makes it possible to run long-running scripts, such as ones that handle complex calculations or access remote resources, without blocking the user interface or other scripts. Web workers provide an easy way to run tasks in the background and improve the overall performance of web applications.
:::

## Use Web Workers

Web Workers are first-class citizens of Rspack, which means you don't need any loader to use web workers directly in Rspack or Rsbuild projects.

For example, create a file called `worker.js`:

```js title=worker.js
self.onmessage = (event) => {
const result = event.data * 2;
self.postMessage(result);
};
```

Then use this worker in the main thread:

```js title=index.js
const worker = new Worker(new URL('./worker.js', import.meta.url));

worker.onmessage = (event) => {
console.log('The results from Workers:', event.data);
};

worker.postMessage(10);
```
### Loading scripts from remote URLs (cross-origin)
By default, the worker script will be emitted as a separate chunk. This script supports uploading to CDN, but must obey the [same-origin policy](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy).
If you want your worker scripts to be accessible across domains, a common solution is to load via [importScripts](https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/importScripts) (not subject to CORS), you can refer to the following code:
```js title=index.js {2}
// https://github.com/jantimon/remote-web-worker
import 'remote-web-worker';

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

worker.onmessage = (event) => {
console.log('The results from Workers:', event.data);
};

worker.postMessage(10);
```
For detailed discussions on cross-domain issues, please refer to [Discussions - webpack 5 web worker support for CORS?](https://github.com/webpack/webpack/discussions/14648)
## Build Web Workers outputs
Rsbuild supports building Web Workers outputs independently, which is helpful when you need to provide Web Workers outputs for use by other applications.
You can set Rsbuild's [output.target](/config/output/target) configuration to `'web-worker'`, and Rsbuild will generate build outputs suitable for the Web Workers environment.
```ts
export default {
output: {
target: 'web-worker',
},
};
```
6 changes: 2 additions & 4 deletions website/docs/zh/config/output/target.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -76,10 +76,6 @@ export default {

指运行在 [Web Worker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) 环境的产物。

:::tip Web Worker
Web Worker 是一种 JavaScript API,它允许网页在后台线程中执行脚本,与主线程(网页)分离。这意味着,您可以使用 Web Worker 来执行计算密集型或长时间运行的任务,而无需阻塞主线程,进而影响网页的性能。
:::

`target` 设置为 `'web-worker'` 时,Rsbuild 会进行以下处理:

- 将 Rspack 的 [target](https://rspack.dev/config/target) 设置为 `'webworker'`
Expand All @@ -88,6 +84,8 @@ Web Worker 是一种 JavaScript API,它允许网页在后台线程中执行脚
- 不会开启默认的拆包策略,**并且 dynamic import 也不会生效**,因为 Web Worker 仅运行支持单个 JavaScript 文件。
- 不会开启热更新相关的能力。

更多信息可参考 [使用 Web Workers](/guide/basic/web-workers)

## 其他 target

Rspack 支持的 [target](https://rspack.dev/config/target) 类型更为丰富,比如 `electron-main``electron-renderer` 等。
Expand Down
1 change: 1 addition & 0 deletions website/docs/zh/guide/basic/_meta.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"typescript",
"tailwindcss",
"unocss",
"web-workers",
"static-deploy",
"upgrade-rsbuild"
]
69 changes: 69 additions & 0 deletions website/docs/zh/guide/basic/web-workers.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# 使用 Web Workers

本文将介绍在 Rsbuild 项目中如何配置和使用 [Web Workers](https://developer.mozilla.org/zh-CN/docs/Web/API/Web_Workers_API/Using_web_workers)

:::tip Web Workers
Web Workers 是一种 JavaScript API,它允许网页在后台线程中执行脚本,与主线程(网页)分离。这意味着,您可以使用 Web Workers 来执行计算密集型或长时间运行的任务,而无需阻塞主线程,进而影响网页的性能。
:::

## 使用 Web Workers

Web Workers 是 Rspack 的一等公民,这意味着你不需要任何的 Loader 就可以直接在 Rspack / Rsbuild 项目中使用 Web Workers。详情可参考 [Rspack - Web Workers](https://rspack.dev/zh/guide/features/web-workers)

例如,创建一个名为 worker.js 的文件:

```js title=worker.js
self.onmessage = (event) => {
const result = event.data * 2;
self.postMessage(result);
};
```

然后在主线程中使用这个 worker:

```js title=index.js
const worker = new Worker(new URL('./worker.js', import.meta.url));

worker.onmessage = (event) => {
console.log('The results from Workers:', event.data);
};

worker.postMessage(10);
```
### 从远程 URL 加载脚本(跨域)
默认情况下,worker 脚本会输出成一个独立的 chunk。worker 脚本支持上传到 CDN,但在加载远程脚本时需要遵守[同源策略](https://developer.mozilla.org/zh-CN/docs/Web/Security/Same-origin_policy)。
如果你希望你的 worker 脚本可以跨域访问,常见解法是通过 [importScripts](https://developer.mozilla.org/zh-CN/docs/Web/API/WorkerGlobalScope/importScripts) (不受 CORS 约束) 加载,可参考如下代码:
```js title=index.js {2}
// https://github.com/jantimon/remote-web-worker
import 'remote-web-worker';

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

worker.onmessage = (event) => {
console.log('The results from Workers:', event.data);
};

worker.postMessage(10);
```
关于跨域问题的详细讨论可参考 [Discussions - webpack 5 web worker support for CORS?](https://github.com/webpack/webpack/discussions/14648)
## 构建 Web Workers 产物
Rsbuild 支持独立构建 Web Workers 产物,这在你需要将 Web Workers 产物提供给其他应用使用时很有帮助。
将 Rsbuild 的 [output.target](/config/output/target) 配置项设置为 `'web-worker'`,即可生成运行在 Worker 线程的构建产物。
```ts
export default {
output: {
target: 'web-worker',
},
};
```

0 comments on commit d9acb8e

Please sign in to comment.