rust
WebAssembly

[Note] Compile Rust to WebAssembly on Mac

Install necessary modules from Homebrew

  • cmake
  • emscripten
$brew install cmake emscripten

After installing emscripten, you can see text like following on console.

Manually set LLVM_ROOT to
  /usr/local/opt/emscripten/libexec/llvm/bin
  and comment out BINARYEN_ROOT
  in ~/.emscripten after running `emcc` for the first time.

Modified ~/.emscripten

I modified my ~/.emscripten like this after calling emcc once.

# this helps projects using emscripten find it
EMSCRIPTEN_ROOT = os.path.expanduser(os.getenv('EMSCRIPTEN', '/usr/local/Cellar/emscripten/1.37.27/libexec')) # directory
#LLVM_ROOT = os.path.expanduser(os.getenv('LLVM', '/usr/bin')) # directory
LLVM_ROOT = os.path.expanduser(os.getenv('LLVM', '/usr/local/opt/emscripten/libexec/llvm/bin')) # directory

# Manually set LLVM_ROOT to
#   /usr/local/opt/emscripten/libexec/llvm/bin
#   and comment out BINARYEN_ROOT
#   in ~/.emscripten after running `emcc` for the first time.
#
# BINARYEN_ROOT = os.path.expanduser(os.getenv('BINARYEN', '')) # if not set, we will use it from ports

# If not specified, defaults to sys.executable.

Compile

In root directory of your project, run following.

# compile a specific file.
rustc --target=wasm32-unknown-emscripten src/main.rs -o dist/main.js

# build you project into wasm
cargo build --target=wasm32-unknown-emscripten