Rust Compilation Target to JS with Emscripten

Bambang Purnomosidi D. P.
2 min readDec 23, 2016

--

Just for the record, I am trying to cross compile Rust source code to JavaScript (asmjs and WebAssembly) but could not get them compiled. Later on I realize from Rustup manual that I need to install target for both asmjs and WebAssembly first. So, since I already got my Emscripten installed, just install those two targets:

rustup target add wasm32-unknown-emscripten

for WebAssembly, and:

rustup target add wasm32-unknown-emscripten

for asmjs.

Now I can compile Rust to js:

rustc — target=asmjs-unknown-emscripten hello.rs

Here’s the result from hello.rs:

fn main() { println!(“Hello, Emscripten!”); }

hello.js:

$ ls
total 1048
drwxr-xr-x 1 bpdp users 32 Dec 23 19:28 .
drwxr-xr-x 1 bpdp users 54 Dec 23 16:16 ..
-rw-r — r — 1 bpdp users 1066117 Dec 23 19:28 hello.js
-rw-r — r — 1 bpdp users 46 Dec 23 16:16 hello.rs
$ node hello.js
Hello, Emscripten!
$

1,066,117 bytes. Quite big, compared with C++ source code which is compiled directly by Emscripten using emcc hello.cpp

#include <stdio.h>

class Test {}; // This will fail in C mode

int main() {
printf(“hello, world!\n”);
return 0;
}

Here’s the result:

$ ls
total 300
drwxr-xr-x 1 bpdp users 54 Dec 23 16:16 .
drwxr-xr-x 1 bpdp users 414 Dec 23 15:57 ..
-rw-r — r — 1 bpdp users 301027 Dec 23 16:13 a.out.js
-rw-r — r — 1 bpdp users 121 Dec 23 15:57 hello_world.cpp
drwxr-xr-x 1 bpdp users 32 Dec 23 19:28 rust
$

C++ version: 301,027 bytes. Since this compilation target is still experimental, I hope things will get better.

--

--

Bambang Purnomosidi D. P.

Software technology wanderer. Half geek. FOSS guy. Believe in open governance. Old stager. Love to code, except for front-end development.