Setting up your first Leptos Project

July 23, 2024

Leptos Rust

Integrating markdown .MD files into a SvelteKit project.


Setting up the Rust project

For this part of the tutorial we mainly follow the Leptos Book. Create a new rust project

cargo new rustle
cd rustle
cargo add leptos --features=csr,nightly

rustup toolchain install nightly
rustup default nightly
rustup target add wasm32-unknown-unknown

Create an index.html in the root directory

<!DOCTYPE html>
<html>
  <head></head>
  <body></body>
</html>

And replace the contents of src/main.rs with

use leptos::*;

fn main() {
    mount_to_body(|| view! { <p>"Hello, world!"</p> })
}

Now install Trunk

cargo install trunk

Now you have a bare-bones Leptos project, now you can run the app

trunk serve

And head over to the browser at http://127.0.0.1:8080/ and see the app in action!

Adding Routing

Add the leptos_router crate

cargo add leptos_router --features=csr

In src/main.rs

use leptos::*;
use leptos_router::*;

#[component]
pub fn App() -> impl IntoView {
	view! {
	<Router>
		<nav>
			<a href="/">Home</a>
			<a href="/about">About</a>
		</nav>
		<main>
			<Routes>
				<Route path="/" view=|| view! { Home Page }/>
				<Route path="/about" view=|| view! { About Page }/>
			</Routes>
		</main>
	</Router>
	}
}

fn main() {
	mount_to_body(App)
}

Now run your app folder run trunk serve --open, and you should be presented with a basic navigation and the ability to navigate between pages.

Optional: VS Code | Rust Analyzer Setup

Add the leptosfmt tool to cargo

cargo install leptosfmt

Copy the following into .vscode/settings.json to get intellisense in your Leptos project.

{
	"rust-analyzer.procMacro.ignored": {
		"leptos_macro": [
		// optional:
		// "component",
		"server"
		],
	},
	"emmet.includeLanguages": {
		"rust": "html",
		"*.rs": "html"
	},
	"tailwindCSS.includeLanguages": {
		"rust": "html",
		"*.rs": "html"
	},
		"files.associations": {
		"*.rs": "rust"
	},
	"editor.quickSuggestions": {
		"other": "on",
		"comments": "on",
		"strings": true
	},
	"css.validate": false,
	"rust-analyzer.rustfmt.overrideCommand": [
		"leptosfmt",
		"--stdin",
		"--rustfmt"
	],
	"rust-analyzer.server.extraEnv": {
		"RUSTUP_TOOLCHAIN": "nightly"
	}
}