JavaScript 又迎来了新的对手:WASM。
这一次,JavaScript会被取代吗?
从JavaScript的历史来看,恐怕不会……
不过,了解一下WASM倒是未尝不可。
最近,在MacOS上尝试了一下WASM。
官方上手教程:https://webassembly.org/getting-started/developers-guide/
emsdk = Emscripten SDK,是一个工具库,用来编译输出wasm。
mac上安装非常简单:
- $ git clone https://github.com/emscripten-core/emsdk.git
- $ cd emsdk
- $ ./emsdk install latest
- $ ./emsdk activate latest
-
完成后,设置一下环境变量。
- $ source ./emsdk_env.sh --build=Release
-
- $ mkdir hello
- $ cd hello
- $ cat << EOF > hello.c
- #include <stdio.h>
- int main(int argc, char ** argv) {
- printf("Hello, world!\n");
- }
- EOF
-
- $ emcc hello.c -o hello.html
-
这会在当前目录下生成3个文件
注意:如果直接用浏览器打开hello.html的话,会无法正常运行。
官方说法
Finally, to actually run the program, we cannot simply open the HTML file in a web browser because cross-origin requests are not supported for the file protocol scheme. We have to actually serve the output files over HTTP.
正确的姿势是启动一个web server。
如果你没有自己的webserver,emsdk已经集成了这个服务,方便测试。
命令
- $ emrun --no_browser --port 8080 .
-
看到这个输出,就表示一切正常了。
然后用浏览器打开:
hello.html
hello.js
hello.wasm