基本用法
让我们实现相当于"你好,世界!"的示例
注意:目前这个项目使用最新Rust,你可以通过 rustup ,并使用
rustup default nightly;描述*如何通过 比目前支持更丰富的类型 进行通信. 该wasm-bindgen工具将解释此信息,且在 wasm文件 更换模块 .
之前的js_hello_world.wasm文件, 被解释为它是一个 ES6模块. 而后来wasm-bindgen生成的js_hello_world.js, 是应该具有 wasm文件 的预期接口,特别是 字符串,类 等丰富类型.
wasm-bindgen工具还会生成, 实现此模块所需的一些其他文件. 例如: js_hello_world_bg.wasm是原始的wasm文件,但是经过处理的. 这是被依赖的js_hello_world_bg.wasm文件,就像之前一样,文件就像一个ES6模块.
js_hello_world.js 调用了js_hello_world_bg.wasm
注意 js_hello_world
_bg.wasm 和 js_hello_world.wasm 的不同
此时,您可能会将这些文件插入更大的构建系统. wasm-bindgen生成的文件像普通的 ES6模块 一样 (wasm文件就已经被使用了) . 截至撰写本文时,很遗憾没有很多工具本身可以做到这一点,但 Webpack的4.0测试版本 有本机的支持! 让我们来看看它,看看它是如何工作的.
首先创建一个index.js文件:
const js = import("./js_hello_world");
js.then(js => {
  js.greet("World!");
});
请注意,我们正在使用import(..)这里因为Webpack不支持同步从主块导入模块.
接下来我们通过创建一个JS依赖项package.json:
{
  "scripts": {
    "serve": "webpack-dev-server"
  },
  "devDependencies": {
    "webpack": "^4.0.1",
    "webpack-cli": "^2.0.10",
    "webpack-dev-server": "^3.1.0"
  }
}
和我们的 webpack 配置
// webpack.config.js
const path = require('path');
module.exports = {
  entry: "./index.js",
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "index.js",
  },
  mode: "development"
};
我们对应的index.html:
<html>
  <head>
    <meta content="text/html;charset=utf-8" http-equiv="Content-Type"/>
  </head>
  <body>
    <script src='./index.js'></script>
  </body>
</html>
最后:
$ npm install
$ npm run serve
如果你打开本地主机: 8080在浏览器中你应该看到一个Hello, world!对话框弹出!
如果这一切都有点多,不用担心!您可以[在线执行此代码][hello-online]谢谢WebAssembly Studio或者你可以跟随GitHub查看所有必需的文件,以及设置它的脚本.