> For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt.

# Wasm

Rsbuild 提供了对 WebAssembly (WASM) 模块的原生支持，允许在项目中直接导入和使用 `.wasm` 资源。

:::tip 什么是 WebAssembly
WebAssembly（缩写为 wasm）是一种可移植、高性能的字节码格式，被设计用来在现代 Web 浏览器中执行 CPU 密集型计算任务，为 Web 平台带来了接近本地编译代码的性能和可靠性。
:::

## 引用方式

你可以在 JavaScript 文件中通过具名导入来引用一个 WebAssembly 模块：

```js title="index.js"
import { add } from './add.wasm';

console.log(add); // [native code]
console.log(add(1, 2)); // 3
```

也可以通过 dynamic import 来引用 WebAssembly 模块：

```js title="index.js"
import('./add.wasm').then(({ add }) => {
  console.log('---- Async Wasm Module');
  console.log(add); // [native code]
  console.log(add(1, 2)); // 3
});
```

还可以通过 `new URL` 语法来获取 WebAssembly 模块的路径：

```js title="index.js"
const wasmURL = new URL('./add.wasm', import.meta.url);

console.log(wasmURL.pathname); // "/static/wasm/[contenthash:10].module.wasm"
```

## Source import

你可以使用 [Source Phase Imports](https://github.com/tc39/proposal-source-phase-imports) 获取编译后的 `WebAssembly.Module`，而不是直接获取模块导出：

```js title="index.js"
import source wasmModule from './add.wasm';

const instance = await WebAssembly.instantiate(wasmModule);
const { add } = instance.exports;

console.log(add(1, 2)); // 3
```

当你需要手动实例化 Wasm 模块、使用不同的 imports 创建多个实例，或将模块传递给 worker 时，这种方式会很有用。

:::tip
`import source` 用法在 Rsbuild v2.1.0 及以上版本中支持。
:::

## 输出目录

当 `.wasm` 资源被引用后，默认会被 Rsbuild 输出到 `dist/static/wasm` 目录下。

你可以通过 [output.distPath](/zh/config/output/dist-path.md) 配置项来修改 `.wasm` 产物的输出目录。

```ts
export default {
  output: {
    distPath: {
      wasm: 'resource/wasm',
    },
  },
};
```

## 类型声明

当你在 TypeScript 代码中引用 Wasm 文件时，通常需要添加相应的类型声明。

比如 `add.wasm` 文件导出了 `add()` 方法，那么你可以在同级目录下创建一个 `add.wasm.d.ts` 文件，并添加相应的类型声明：

```ts title="add.wasm.d.ts"
export const add: (num1: number, num2: number) => number;
```
