Movatterモバイル変換


[0]ホーム

URL:


Skip to content
Cloudflare Docs
Log in

Wasm can be used from within a Worker written in JavaScript or TypeScript by importing a Wasm module,and instantiating an instance of this module usingWebAssembly.instantiate(). This can be used to accelerate computationally intensive operations which do not involve significant I/O.

This guide demonstrates the basics of Wasm and JavaScript interoperability.

Simple Wasm Module

In this guide, you will use the WebAssembly Text Format to create a simple Wasm module to understand how imports and exports work. In practice, you would not write code in this format. You would instead use the programming language of your choice and compile directly to WebAssembly Binary Format (.wasm).

Review the following example module (;; denotes a comment):

;; src/simple.wat
(module
;; Import a function from JavaScript named `imported_func`
;; which takes a single i32 argument and assign to
;; variable $i
(func $i (import "imports" "imported_func") (param i32))
;; Export a function named `exported_func` which takes a
;; single i32 argument and returns an i32
(func (export "exported_func") (param $input i32) (result i32)
;; Invoke `imported_func` with $input as argument
local.get $input
call $i
;; Return $input
local.get $input
return
)
)

Usingwat2wasm, convert the WAT format to WebAssembly Binary Format:

Terminal window
wat2wasmsrc/simple.wat-osrc/simple.wasm

Bundling

Wrangler will bundle any Wasm module that ends in.wasm or.wasm?module, so that it is available at runtime within your Worker. This is done using a default bundling rule which can be customized in theWrangler configuration file. Refer toWrangler Bundling for more information.

Use from JavaScript

After you have converted the WAT format to WebAssembly Binary Format, import and use the Wasm module in your existing JavaScript or TypeScript Worker:

TypeScript
importmod from"./simple.wasm";
// Define imports available to Wasm instance.
constimportObject={
imports:{
imported_func:(arg:number)=>{
console.log(`Hello from #"polite">

When invoked, this Worker should logHello from #"auto">Success: 42, demonstrating the ability to invoke Wasm methods with arguments from JavaScript and vice versa.

Next steps

In practice, you will likely compile a language of your choice (such as Rust) to WebAssembly binaries. Many languages provide abindgen to simplify the interaction between JavaScript and Wasm. These tools may integrate with your JavaScript bundler, and provide an API other than the WebAssembly API for initializing and invoking your Wasm module. As an example, refer to theRustwasm-bindgen documentation.

Alternatively, to write your entire Worker in Rust, Workers provides many of the sameRuntime APIs andbindings when using theworkers-rs crate. For more information, refer to theWorkers Rust guide.


[8]
ページ先頭

©2009-2026 Movatter.jp