Closed6

Bun + Nuxt3 + Wasmを試す

TaroTaro

まずBunを入れる

https://bun.sh/

$ curl -fsSL https://bun.sh/install | bash
######################################################################## 100.0%
bun was installed successfully to ~/.bun/bin/bun

Added "~/.bun/bin" to $PATH in "~/.bashrc"

To get started, run:

  source /home/taro137/.bashrc
  bun --help
TaroTaro

Nuxtのプロジェクトを作成

$ bunx nuxi@latest init nuxt-wasm

✔ Which package manager would you like to use?
bun
◐ Installing dependencies...                                                                                9:26:28 PM
bun install v1.0.11 (f7f6233e)
 + @nuxt/devtools@1.0.1
 + nuxt@3.8.1
 + vue@3.3.8
 + vue-router@4.2.5
✔ Types generated in .nuxt                                                                                 9:26:41 PM

 671 packages installed [11.99s]
✔ Installation completed.                                                                                  9:26:41 PM

✔ Initialize git repository?
Yes
ℹ Initializing git repository...                                                                           9:26:43 PM

hint: Using 'master' as the name for the initial branch. This default branch name
hint: is subject to change. To configure the initial branch name to use in all
hint: of your new repositories, which will suppress this warning, call:
hint:
hint:   git config --global init.defaultBranch <name>
hint:
hint: Names commonly chosen instead of 'master' are 'main', 'trunk' and
hint: 'development'. The just-created branch can be renamed via this command:
hint:
hint:   git branch -m <name>
Initialized empty Git repository in /home/taro137/desktop/rust/nuxt-wasm/.git/
                                                                                                            9:26:43 PM
✨ Nuxt project has been created with the v3 template. Next steps:
 › cd nuxt-wasm                                                                                             9:26:43 PM
 › Start development server with bun run dev
TaroTaro

srcディレクトリでcargo new wasm --libする。

src/wasm/Cargo.toml
[package]
name = "wasm"
version = "0.1.0"
edition = "2021"

[lib]
crate-type = ["cdylib", "rlib"]

[features]
default = ["console_error_panic_hook"]

[dependencies]
wasm-bindgen = "0.2.88"
console_error_panic_hook = { version = "0.1.7", optional = true }

[dev-dependencies]
wasm-bindgen-test = "0.3.34"

[profile.release]
opt-level = "s"
TaroTaro

よくある例(JSのalertをRustで呼び出し、RustのgreetをJSで呼び出す)

src/wasm/src/lib.rs
use wasm_bindgen::prelude::*;

#[wasm_bindgen]
extern {
  pub fn alert(msg: &str);
}

#[wasm_bindgen]
pub fn greet(name: &str) {
  alert(&format!("Hello, {}!", name));
}
src/app.vue
<script setup lang="ts">
import init, { greet } from '@/wasm/pkg'

onMounted(async () => {
  await init()
  greet('Wasm via Nuxt3')
})
</script>

<template>
  <div>
    <NuxtWelcome />
  </div>
</template>
このスクラップは2024/02/20にクローズされました