一个基础项目
为了构建 Web 应用程序,trunk
运行多种工具的组合,主要是 cargo build
和 wasm-bindgen
。 因此,拥有一个简单的 cargo
项目和一个 index.html
文件作为入口点就足以让你开始。
创建项目
首先创建一个新的 Rust 项目并进入该文件夹
cargo new trunk-hello-world
cd trunk-hello-world
为 Web 添加一些依赖项
cargo add wasm-bindgen console_error_panic_hook
cargo add web_sys -F Window,Document,HtmlElement,Text
在新创建的项目中,创建一个名为 src/main.rs
的文件,内容如下
use web_sys::window; fn main() { console_error_panic_hook::set_once(); let document = window() .and_then(|win| win.document()) .expect("Could not access the document"); let body = document.body().expect("Could not access document.body"); let text_node = document.create_text_node("Hello, world from Vanilla Rust!"); body.append_child(text_node.as_ref()) .expect("Failed to append text"); }
在项目根目录中创建一个 index.html
文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Hello World</title>
</head>
<body>
</body>
</html>
然后,在该项目内部启动 trunk
以构建和提供服务
trunk serve --open
这将编译项目,运行 wasm_bindgen
,并基于原始文件创建一个 index.html
,该文件加载并初始化应用程序。
应用程序本身非常基础,只是获取文档的 body 并添加一个注释。
下一步
很可能,你不想手动更新应用程序的 DOM 树。 你可能想要添加一些资源、调整构建过程、使用更多浏览器 API、执行一些 HTTP 请求、使用现有的 Web crate,甚至可能与 JavaScript 世界交互。 然而,所有这些都是我们刚刚创建的基础项目的扩展。
这里有一些提示