Deno使用WebGPU遇TS2339错误:Navigator无gpu属性求解决
解决Deno中WebGPU的类型错误与使用问题
1. 修正TypeScript类型配置
你遇到的Property 'gpu' does not exist on type 'Navigator'错误,本质是TypeScript未加载WebGPU的类型定义。修改deno.jsonc,在compilerOptions.lib中添加"webgpu":
{ "compilerOptions": { "lib": [ "dom", "dom.iterable", "dom.asynciterable", "deno.ns", "webgpu" // 新增WebGPU类型库 ] }, "unstable": ["webgpu"], // 其他配置保持不变 }
2. 确保打包时显式启用Unstable特性
即便配置文件声明了"unstable": ["webgpu"],部分Deno命令(包括旧的deno bundle)仍需显式传递--unstable参数才能生效。若坚持使用deno bundle,命令需调整为:
deno bundle --config deno.jsonc --unstable ui/static/script/run.ts bin/static/script/run.js
3. 改用推荐的打包工具(替代弃用的deno bundle)
由于deno bundle将在Deno 2.0移除,推荐使用以下两种替代方案:
方案A:使用deno_emit
- 安装deno_emit依赖:
deno add jsr:@deno/emit
- 创建打包脚本
bundle.ts:
import { bundle } from "@deno/emit"; const result = await bundle("ui/static/script/run.ts", { compilerOptions: { lib: ["dom", "dom.iterable", "dom.asynciterable", "deno.ns", "webgpu"], }, unstable: ["webgpu"], }); await Deno.writeTextFile("bin/static/script/run.js", result.code);
- 运行打包脚本(需加
--unstable):
deno run --unstable --allow-read --allow-write bundle.ts
方案B:使用esbuild
esbuild对WebGPU支持更直接,且打包速度更快:
- 安装esbuild:
deno add esbuild
- 直接执行打包命令:
deno run --allow-read --allow-write npm:esbuild ui/static/script/run.ts --bundle --outfile=bin/static/script/run.js --target=chrome113
指定
--target=chrome113是因为Chrome 113正式支持WebGPU,确保编译后的代码兼容目标浏览器。
4. 验证代码运行
打包完成后,在Chrome 113+等支持WebGPU的浏览器中加载打包后的JS文件,即可正常调用WebGPU API。
内容的提问来源于stack exchange,提问作者goddtriffin
相关产品推荐
相关产品推荐

