| 1 |
# Converting WebAssembly to JS |
| 2 |
|
| 3 |
[View full source code][code] |
| 4 |
|
| 5 |
[code]: https://github.com/rustwasm/wasm-bindgen/tree/master/examples/wasm2js |
| 6 |
|
| 7 |
Not all browsers have support for `WebAssembly` at this time (although all major |
| 8 |
ones do). If you'd like to support older browsers, you probably want a method |
| 9 |
that doesn't involve keeping two codebases in sync! |
| 10 |
|
| 11 |
Thankfully there's a tool from [binaryen] called `wasm2js` to convert a wasm |
| 12 |
file to JS. This JS file, if successfully produced, is equivalent to the wasm |
| 13 |
file (albeit a little bit larger and slower), and can be loaded into practically |
| 14 |
any browser. |
| 15 |
|
| 16 |
This example is relatively simple (cribbing from the [`console.log` |
| 17 |
example](console-log.md)): |
| 18 |
|
| 19 |
```rust |
| 20 |
{{#include ../../../examples/wasm2js/src/lib.rs}} |
| 21 |
``` |
| 22 |
|
| 23 |
The real magic happens when you actually build the app. Just after |
| 24 |
`wasm-bindgen` we see here how we execute `wasm2js` in our build script: |
| 25 |
|
| 26 |
```sh |
| 27 |
{{#include ../../../examples/wasm2js/build.sh}} |
| 28 |
``` |
| 29 |
|
| 30 |
Note that the `wasm2js` tool is still pretty early days so there's likely to be |
| 31 |
a number of bugs to run into or work around. If any are encountered though |
| 32 |
please feel free to report them upstream! |
| 33 |
|
| 34 |
Also note that eventually this will ideally be automatically done by your |
| 35 |
bundler and no action would be needed from you to work in older browsers via |
| 36 |
`wasm2js`! |
| 37 |
|
| 38 |
[binaryen]: https://github.com/WebAssembly/binaryen |