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

Leptos 开发体验优化

Leptos Developer Experience Improvements

有几件事可以改善你使用 Leptos 开发网站和应用程序的体验。你可能需要花几分钟时间设置你的环境来优化开发体验,特别是如果你想跟随本书中的示例进行编码。

There are a couple of things you can do to improve your experience of developing websites and apps with Leptos. You may want to take a few minutes and set up your environment to optimize your development experience, especially if you want to code along with the examples in this book.

1) 设置 console_error_panic_hook

1) Set up console_error_panic_hook

默认情况下,在浏览器中运行 WASM 代码时发生的 panic 只会在浏览器中抛出一个错误,并带有一条毫无帮助的消息,如 Unreachable executed,以及一个指向 WASM 二进制文件的堆栈跟踪。

By default, panics that happen while running your WASM code in the browser just throw an error in the browser with an unhelpful message like Unreachable executed and a stack trace that points into your WASM binary.

使用 console_error_panic_hook,你可以获得一个真实的 Rust 堆栈跟踪,其中包含 Rust 源代码中的行号。

With console_error_panic_hook, you get an actual Rust stack trace that includes a line in your Rust source code.

设置非常简单:

It's very easy to set up:

  1. 在你的项目中运行 cargo add console_error_panic_hook

  2. Run cargo add console_error_panic_hook in your project

  3. 在你的 main 函数中,添加 console_error_panic_hook::set_once();

  4. In your main function, add console_error_panic_hook::set_once();

如果不清楚,点击这里查看示例

If this is unclear, click here for an example.

现在,你应该在浏览器控制台中获得更好的 panic 消息了!

Now you should have much better panic messages in the browser console!

2) 在 #[component]#[server] 内部进行编辑器自动补全

2) Editor Autocompletion inside #[component] and #[server]

由于宏的特性(它们可以将任何内容展开为任何内容,但前提是输入在那一刻必须完全正确),rust-analyzer 可能很难提供适当的自动补全和其他支持。

Because of the nature of macros (they can expand from anything to anything, but only if the input is exactly correct at that instant) it can be hard for rust-analyzer to do proper autocompletion and other support.

如果你在编辑器中使用这些宏时遇到问题,可以明确告诉 rust-analyzer 忽略某些过程宏(proc macros)。特别是对于 #[server] 宏,它注解了函数体,但实际上并不会转换函数体内的任何内容,这会非常有帮助。

If you run into issues using these macros in your editor, you can explicitly tell rust-analyzer to ignore certain proc macros. For the #[server] macro especially, which annotates function bodies but doesn't actually transform anything inside the body of your function, this can be really helpful.

Note

从 Leptos 0.5.3 版本开始,增加了对 #[component] 宏的 rust-analyzer 支持,但如果你遇到问题,也可以考虑将 #[component] 添加到宏忽略列表中(见下文)。 请注意,这意味着 rust-analyzer 将无法识别你的组件属性(props),这可能会在 IDE 中生成它自己的一套错误或警告。

Starting in Leptos version 0.5.3, rust-analyzer support was added for the #[component] macro, but if you run into issues, you may want to add #[component] to the macro ignore list as well (see below). Note that this means that rust-analyzer doesn't know about your component props, which may generate its own set of errors or warnings in the IDE.

VSCode settings.json

VSCode settings.json:

"rust-analyzer.procMacro.ignored": {
	"leptos_macro": [
        // 可选:
        // optional:
		// "component",
		"server"
	],
}

带有 cargo-leptos 的 VSCode settings.json

VSCode with cargo-leptos settings.json:

"rust-analyzer.procMacro.ignored": {
	"leptos_macro": [
        // 可选:
        // optional:
		// "component",
		"server"
	],
},
// 如果由 `ssr` 特性控制的代码显示为非活动状态,
// 你可能需要告诉 rust-analyzer 默认启用 `ssr` 特性
//
// if code that is cfg-gated for the `ssr` feature is shown as inactive,
// you may want to tell rust-analyzer to enable the `ssr` feature by default
//
// 你也可以使用 `rust-analyzer.cargo.allFeatures` 来启用所有特性
// you can also use `rust-analyzer.cargo.allFeatures` to enable all features
"rust-analyzer.cargo.features": ["ssr"]

Neovim:

Neovim:

vim.lsp.config('rust_analyzer', {
  -- 其他配置 ...
  -- Other Configs ...
  settings = {
    ["rust-analyzer"] = {
      -- 其他设置 ...
      -- Other Settings ...
      procMacro = {
        ignored = {
          leptos_macro = {
            -- 可选: --
            -- optional: --
            -- "component",
            "server",
          },
        },
      },
    },
  }
})

Helix,在 .helix/languages.toml 中:

Helix, in .helix/languages.toml:

[[language]]
name = "rust"

[language-server.rust-analyzer]
config = { procMacro = { ignored = { leptos_macro = [
	# 可选:
	# Optional:
	# "component",
	"server"
] } } }

Zed,在 settings.json 中:

Zed, in settings.json:

{
  -- 其他设置 ...
  -- Other Settings ...
  "lsp": {
    "rust-analyzer": {
      "procMacro": {
        "ignored": [
          // 可选:
          // optional:
          // "component",
          "server"
        ]
      }
    }
  }
}

SublimeText 3,在 Goto Anything... 菜单下的 LSP-rust-analyzer.sublime-settings 中:

SublimeText 3, under LSP-rust-analyzer.sublime-settings in Goto Anything... menu:

// 此处的设置将覆盖 "LSP-rust-analyzer/LSP-rust-analyzer.sublime-settings" 中的设置
// Settings in here override those in "LSP-rust-analyzer/LSP-rust-analyzer.sublime-settings"
{
  "rust-analyzer.procMacro.ignored": {
    "leptos_macro": [
      // 可选:
      // optional:
      // "component",
      "server"
    ],
  },
}

3) 在编辑器的 Rust-Analyzer 中启用特性(可选)

3) Enable features in Rust-Analyzer for your Editor (optional)

默认情况下,rust-analyzer 只会针对 Rust 项目中的默认特性(default features)运行。Leptos 使用不同的特性来控制编译。对于客户端渲染(CSR)项目,我们在不同地方使用 csr;对于服务器端渲染(SSR)应用,它们可能包含用于服务器代码的 ssr 和用于仅在浏览器中运行的代码的 hydrate

By default, rust-analyzer will only run against the default features in your Rust project. Leptos uses different features to control compilation. For client side rendered projects, we use csr in different places, for server side rendered apps they can include ssr for server code and hydrate for code that we'll only run in the browser.

如何启用这些特性因 IDE 而异,我们在下面列出了一些常用的设置。如果你的 IDE 未列出,通常可以通过搜索 rust-analyzer.cargo.featuresrust-analyzer.cargo.allFeatures 找到该设置。

How to enable these features varies by your IDE, we've listed some common ones below. If your IDE is not listed, you can usually find the setting by searching for rust-analyzer.cargo.features or rust-analyzer.cargo.allFeatures.

VSCode,在 settings.json 中:

VSCode, in settings.json:

{
  "rust-analyzer.cargo.features": "all",  // 启用所有特性
  // "rust-analyzer.cargo.features": "all",  // Enable all features
}

Neovim,在 init.lua 中:

Neovim, in init.lua:

vim.lsp.config('rust_analyzer', {
  settings = {
    ["rust-analyzer"] = {
      cargo = {
        features = "all", -- 启用所有特性
        -- features = "all", -- Enable all features
      },
    },
  }
})

helix,在 .helix/languages.toml 或每个项目的 .helix/config.toml 中:

helix, in .helix/languages.toml or per project in .helix/config.toml:

[[language]]
name = "rust"

[language-server.rust-analyzer.config.cargo]
allFeatures = true

Zed,在 settings.json 中:

Zed, in settings.json:

{
  -- 其他设置 ...
  -- Other Settings ...
  "lsp": {
    "rust-analyzer": {
      "initialization_options": {
        "cargo": {
          "allFeatures": true // 启用所有特性
          // "allFeatures": true // Enable all features
        }
      }
	}
  }
}

SublimeText 3,在 LSP-rust-analyzer-settings.json 的用户设置中:

SublimeText 3,in the user settings for LSP-rust-analyzer-settings.json

 {
        "settings": {
            "LSP": {
                "rust-analyzer": {
                    "settings": {
                        "cargo": {
                            "features": "all"
                        }
                    }
                }
            }
        }
    }

4) 设置 leptosfmt(可选)

4) Set up leptosfmt (optional)

leptosfmt 是一个用于 Leptos view! 宏(通常在其中编写 UI 代码)的格式化工具。由于 view! 宏启用了一种 “RSX”(类似于 JSX)风格的 UI 编写方式,cargo-fmt 很难自动格式化 view! 宏内部的代码。leptosfmt 是一个解决格式化问题并保持 RSX 风格 UI 代码整洁的 crate!

leptosfmt is a formatter for the Leptos view! macro (inside of which you'll typically write your UI code). Because the view! macro enables an 'RSX' (like JSX) style of writing your UI's, cargo-fmt has a harder time auto-formatting your code that's inside the view! macro. leptosfmt is a crate that solves your formatting issues and keeps your RSX-style UI code looking nice and tidy!

leptosfmt 可以通过命令行或在代码编辑器中安装和使用:

leptosfmt can be installed and used via the command line or from within your code editor:

首先,使用 cargo install leptosfmt 安装该工具。

First, install the tool with cargo install leptosfmt.

如果你只想在命令行中使用默认选项,只需在项目根目录下运行 leptosfmt ./**/*.rs 即可使用 leptosfmt 格式化所有 Rust 文件。

If you just want to use the default options from the command line, just run leptosfmt ./**/*.rs from the root of your project to format all the rust files using leptosfmt.

在支持 Rust Analyzer 的 IDE 中自动运行

Run automatically in Rust Analyzer IDEs

如果你希望设置编辑器以配合 leptosfmt 使用,或者希望自定义 leptosfmt 体验,请参阅 leptosfmt GitHub 仓库 README.md 页面上的说明。

If you wish to set up your editor to work with leptosfmt, or if you wish to customize your leptosfmt experience, please see the instructions available on the leptosfmt github repo's README.md page.

请注意,为了获得最佳效果,建议在每个工作区的基础上为编辑器设置 leptosfmt

Just note that it's recommended to set up your editor with leptosfmt on a per-workspace basis for best results.

在 RustRover 中自动运行

Run automatically in RustRover

遗憾的是,RustRover 不支持 Rust Analyzer,因此需要采用不同的方法来自动运行 leptosfmt。一种方法是使用 FileWatchers 插件并进行以下配置:

Unfortunately, RustRover does not support Rust Analyzer, so a different approach is required in order to automatically run leptosfmt. One way is to use the FileWatchers plugin with the below configuration:

  • 名称 (Name): Leptosfmt
  • 文件类型 (File type): Rust files
  • 程序 (Program): /path/to/leptosfmt(如果它在你的 $PATH 环境变量中,可以简写为 leptosfmt
  • 参数 (Arguments): $FilePath$
  • 刷新输出路径 (Output paths to refresh): $FilePath$

5) 开发期间使用 --cfg=erase_components

5) Use --cfg=erase_components during development

Leptos 0.7 对渲染器进行了许多更改,使其更加依赖类型系统。对于大型项目,这可能会导致编译速度变慢。通过在开发期间使用自定义配置标志 --cfg=erase_components,可以缓解大部分编译变慢的情况。(这会擦除部分类型信息,以减少编译器的工作量和发出的调试信息,代价是增加二进制文件大小和运行时开销,因此最好不要在发布(release)模式下使用它。)

Leptos 0.7 made a number of changes to the renderer that relied more heavily on the type system. For larger projects, this can lead to slower compile times. Most of the slowdown in compile times can be alleviated by using the custom configuration flag --cfg=erase_components during development. (This erases some of that type information to reduce the amount of work done and debug info emitted by the compiler, at the expense of additional binary size and runtime cost, so it’s best not to use it in release mode.)

从 cargo-leptos v0.2.40 开始,这在开发模式下会自动为你启用。如果你使用的是 trunk,不使用 cargo-leptos,或者想为非开发用途启用它,可以在命令行中轻松设置(RUSTFLAGS="--cfg erase_components" trunk serveRUSTFLAGS="--cfg erase_components" cargo leptos watch),或者在你的 .cargo/config.toml 中设置:

As of cargo-leptos v0.2.40, this is automatically enabled for you in development mode. If you are using trunk, not using cargo-leptos, or want to enable it for non-dev uses, you can set this easily in the command line (RUSTFLAGS="--cfg erase_components" trunk serve or RUSTFLAGS="--cfg erase_components" cargo leptos watch), or in your .cargo/config.toml:

# 使用你自己的原生目标 (target)
# use your own native target
[target.aarch64-apple-darwin]
rustflags = [
  "--cfg",
  "erase_components",
]

[target.wasm32-unknown-unknown]
rustflags = [
   "--cfg",
   "erase_components",
]