Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

cargo-leptos 简介

Introducing cargo-leptos

到目前为止,我们只是在浏览器中运行代码,并使用 Trunk 来协调构建过程以及运行本地开发流程。如果我们要添加服务器端渲染,我们将需要在服务器上运行我们的应用程序代码。这意味着我们需要构建两个独立的二进制文件,一个编译为本地代码(native code)并在服务器上运行,另一个编译为 WebAssembly (WASM) 并在用户的浏览器中运行。此外,服务器需要知道如何将这个 WASM 版本(以及初始化它所需的 JavaScript)提供给浏览器。

So far, we’ve just been running code in the browser and using Trunk to coordinate the build process and run a local development process. If we’re going to add server-side rendering, we’ll need to run our application code on the server as well. This means we’ll need to build two separate binaries, one compiled to native code and running the server, the other compiled to WebAssembly (WASM) and running in the user’s browser. Additionally, the server needs to know how to serve this WASM version (and the JavaScript required to initialize it) to the browser.

这并不是一个不可逾越的任务,但它增加了一些复杂性。为了方便起见,并提供更轻松的开发体验,我们构建了 cargo-leptos 构建工具。cargo-leptos 的存在基本上是为了协调应用的构建过程,处理在你进行更改时对服务器和客户端两部分进行重新编译,并为 Tailwind、SASS 和测试等功能添加了一些内置支持。

This is not an insurmountable task but it adds some complication. For convenience and an easier developer experience, we built the cargo-leptos build tool. cargo-leptos basically exists to coordinate the build process for your app, handling recompiling the server and client halves when you make changes, and adding some built-in support for things like Tailwind, SASS, and testing.

入门非常简单。只需运行:

Getting started is pretty easy. Just run

cargo install --locked cargo-leptos

然后,要创建一个新项目,你可以运行:

And then to create a new project, you can run either

# 使用 Actix 模板
# for an Actix template
cargo leptos new --git https://github.com/leptos-rs/start-actix

或者:

or

# 使用 Axum 模板
# for an Axum template
cargo leptos new --git https://github.com/leptos-rs/start-axum

确保你已经添加了 wasm32-unknown-unknown 目标,这样 Rust 才能将你的代码编译为 WebAssembly 以在浏览器中运行。

Make sure you've added the wasm32-unknown-unknown target so that Rust can compile your code to WebAssembly to run in the browser.

rustup target add wasm32-unknown-unknown

现在 cd 进入你创建的目录并运行:

Now cd into the directory you’ve created and run

cargo leptos watch

一旦应用编译完成,你就可以在浏览器中打开 http://localhost:3000 来查看它。

Once your app has compiled you can open up your browser to http://localhost:3000 to see it.

cargo-leptos 拥有许多额外功能和内置工具。你可以在 它的 README 中了解更多。

cargo-leptos has lots of additional features and built in tools. You can learn more in its README.

但是,当你打开浏览器访问 localhost:3000 时,到底发生了什么?请继续阅读以寻找答案。

But what exactly is happening when you open your browser to localhost:3000? Well, read on to find out.