1

在现代前

 3 years ago
source link: https://blog.rxliuli.com/p/0171bcd51b1343d6a9ad54557d567c46/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
在现代前端项目中使用 Worker

在现代_

2020年12月30日 下午

329 字

4 分钟

本文最后更新于:2021年6月19日 凌晨

由于需要在 Browser 进行大量的计算,所以吾辈开始尝试使用 webworker 分离 CPU 密集型的计算操作,最终找到了 comlink 这个库,但之前在 vue 中使用时发生了错误,目前看起来已经得到了解决,所以在此记录一下。

主要分为两类

  • 浏览器上的 WebWorker/SharedWorker
  • nodejs 中的 worker_threads

目前 vite 对此默认支持,不再需要配置插件,仅使用 comlink 即可。

1
2
3
4
5
6
7
8
// hello.worker.ts
import { expose } from "comlink";

export function hello(name: string) {
return `hello ${name}`;
}

expose(hello);
1
2
3
4
5
6
7
8
9
// main.ts
import type { hello } from "./hello.worker";
import HelloWorker from "./hello.worker?worker";
import { wrap } from "comlink";
(async () => {
const asyncHello = wrap<typeof hello>(new HelloWorker());
const res = await asyncHello("liuli");
console.log(res);
})();

nodejs

  • rollup-plugin-web-worker-loader
    • 默认不会处理 ts 文件
    • worker 中包含依赖时不会捆绑
  • rollup-plugin-worker-factory
    • 没有看到 ts 的示例
    • 默认会修改 Worker
  • @surma/rollup-plugin-off-main-thread
    • 没有看到 ts 的示例

目前没有找到满意的插件,后续可能不得不写一个 rollup 插件。还是那句话,没有对比就没有伤害,如果没有 vite 对 ts+worker 的良好支持,或许吾辈还能忍受这种糟糕的开发体验。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK