Upgrade to Pro — share decks privately, control downloads, hide ads and more …

WebAssemblyでオセロを作ってみた

t-yng
October 12, 2021

 WebAssemblyでオセロを作ってみた

t-yng

October 12, 2021
Tweet

More Decks by t-yng

Other Decks in Technology

Transcript

  1. wasmͷϓϩδΣΫτ࡞੒ $ cargo new --lib wasm . ᵓᴷ package.json └─

    wasm ᵓᴷ Cargo.toml └─ src └─ lib.rs ͜͜ʹ࣮૷Λॻ͍͍ͯ͘
  2. RustΛ࣮૷ͯ͠ΈΔ extern crate wasm_bindgen; use wasm_bindgen::prelude::*; #[wasm_bindgen] pub fn add(a:

    i32, b: i32) -> i32 { a + b; } #[wasm_bindgen] Ͱ JavaScript͔Β add ؔ਺Λݺͼग़͠ 
 Մೳʹ͢Δ
  3. Cargo.tomlͷઃఆ [package] name = "wasm" version = "0.1.0" edition =

    "2018" [lib] crate-type = ["cdylib"] [dependencies] wasm-bindgen="0.2" Cargo.toml: CargoͷઃఆϑΝΠϧ (package.jsonΈ͍ͨͳϞϊ) ɾlibͷλΠϓΛ cdylib ʹઃఆ͢Δ ɾdependencies ʹ wasm-bindgen Λ௥Ճ
  4. WasmʹίϯύΠϧ͢Δ . ᵓᴷ package.json ᵓᴷ src │ɹ └─ lib │ɹɹ

    └─ wasm │ɹɹɹɹ ᵓᴷᴷ package.json │ ɹɹɹɹ ᵓᴷᴷ wasm.d.ts │ ɹɹɹɹᵓᴷᴷ wasm.js │ɹɹɹɹ ᵓᴷᴷ wasm_bg.js │ ɹɹɹɹᵓᴷᴷ wasm_bg.wasm │ ɹɹɹɹᵋᴷᴷ wasm_bg.wasm.d.ts └─ wasm ɹɹᵓᴷ Cargo.toml ɹɹ └─ src ɹɹɹ ɹᵋᴷ lib.rs XBTNQBDLͰ Ϗϧυͨ͠੒Ռ෺
  5. Next.jsͰϑϩϯτΤϯυΛߏங . ᵓᴷ package.json ᵓᴷ next.con fi g.js ᵓᴷ src

    │ ᵓᴷ lib │ ɹᴹ ɹ └─ wasm │ └─ pages │ ɹɹᵋᴷ index.jsx └─ wasm $ yarn install next react react-dom Next.jsΛ࢖͏͜ͱͰ࠷খߏ੒ͰWasmΛࢼ͢͜ͱ͕Ͱ͖Δ ࣍εϥΠυͰ࡞੒༧ఆ ࣍εϥΠυͰ࡞੒༧ఆ
  6. Next.con fi g.js Λઃఆ // next.con fi g.js module.exports =

    { webpack(config) { // next build Λ͢Δ৔߹͸͜Ε͚ͩͩͱμϝ config.experiments = { asyncWebAssembly: true }; return config; }, }; $ touch next.con fi g.js
  7. src/pages/index.js Λ࣮૷ import { add } from "../lib/wasm/wasm_bg"; const IndexPage

    = () => { return <button onClick={() => alert(add(10, 20))}>଍͠ࢉ</button>; }; export default IndexPage; Webpack5 Ͱ͸ wasmͷಡΈࠐΈΛαϙʔτ͍ͯ͠Δ WebAssembly.instantiateStreaming Λ࢖ͬͯ wasm ΛಡΈ ࠐΉܗࣜʹม׵ͯ͘͠Ε͍ͯΔ XFCQBDLFYBNQMFTXBTNTJNQMF $ mkdir -p src/pages && touch src/pages/index.jsx