Skip to content

Commit 00b21ed

Browse files
authored
Merge pull request #801 from vitejs/sync-e11dd91e-1
docs(en): merge docs-cn/sync-docs into docs-cn/dev @ e11dd91
2 parents c469c0b + 3ac42db commit 00b21ed

File tree

1 file changed

+46
-4
lines changed

1 file changed

+46
-4
lines changed

guide/features.md

Lines changed: 46 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -500,7 +500,8 @@ const module = await import(`./dir/${file}.js`)
500500

501501
## WebAssembly {#webassembly}
502502

503-
预编译的 `.wasm` 文件可以通过 `?init` 来导入。默认导出一个初始化函数,返回值为所导出 wasm 实例对象的 Promise:
503+
预编译的 `.wasm` 文件可以通过 `?init` 来导入。
504+
默认导出一个初始化函数,返回值为所导出 [`WebAssembly.Instance`](https://developer.mozilla.org/en-US/docs/WebAssembly/JavaScript_interface/Instance) 实例对象的 Promise:
504505

505506
```js
506507
import init from './example.wasm?init'
@@ -510,7 +511,7 @@ init().then((instance) => {
510511
})
511512
```
512513

513-
`init` 函数还可以将传递给 `WebAssembly.instantiate` 的导入对象作为其第二个参数:
514+
`init` 函数还可以将传递给 [`WebAssembly.instantiate`](https://developer.mozilla.org/en-US/docs/WebAssembly/JavaScript_interface/instantiate) 的导入对象作为其第二个参数:
514515

515516
```js
516517
init({
@@ -524,13 +525,54 @@ init({
524525
})
525526
```
526527

527-
在生产构建当中,体积小于 `assetInlineLimit``.wasm` 文件将会被内联为 base64 字符串。否则,它们将作为资源复制到 `dist` 目录中,并按需获取。
528+
在生产构建当中,体积小于 `assetInlineLimit``.wasm` 文件将会被内联为 base64 字符串。否则,它们将被视为 [静态资源](./assets) ,并按需获取。
528529

529-
::: warning
530+
::: tip 注意
530531
[对 WebAssembly 的 ES 模块集成提案](https://github.com/WebAssembly/esm-integration) 尚未支持。
531532
请使用 [`vite-plugin-wasm`](https://github.com/Menci/vite-plugin-wasm) 或其他社区上的插件来处理。
532533
:::
533534

535+
### 访问 WebAssembly 模块 {#accessing-the-webassembly-module}
536+
537+
如果需要访问 `Module` 对象,例如将它多次实例化,可以使用 [显式 URL 引入](./assets#explicit-url-imports) 来解析资源,然后执行实例化:
538+
539+
```js
540+
import wasmUrl from 'foo.wasm?url'
541+
542+
const main = async () => {
543+
const responsePromise = fetch(wasmUrl)
544+
const { module, instance } = await WebAssembly.instantiateStreaming(
545+
responsePromise,
546+
)
547+
/* ... */
548+
}
549+
550+
main()
551+
```
552+
553+
### 在 Node.js 中获取模块 {#fetching-the-module-in-node-js}
554+
555+
在 SSR 中,作为 `?init` 导入的 `fetch()` 可能会失败,导致 `TypeError: Invalid URL` 报错。
556+
请参见问题 [在 SSR 中支持 wasm](https://github.com/vitejs/vite/issues/8882)
557+
558+
以下是一种替代方案,假设项目根目录在当前目录:
559+
560+
```js
561+
import wasmUrl from 'foo.wasm?url'
562+
import { readFile } from 'node:fs/promises'
563+
564+
const main = async () => {
565+
const resolvedUrl = (await import('./test/boot.test.wasm?url')).default
566+
const buffer = await readFile('.' + resolvedUrl)
567+
const { instance } = await WebAssembly.instantiate(buffer, {
568+
/* ... */
569+
})
570+
/* ... */
571+
}
572+
573+
main()
574+
```
575+
534576
## Web Workers {#web-workers}
535577

536578
### 通过构造器导入 {#import-with-constructors}

0 commit comments

Comments
 (0)