I've been trying my best to use a scoped CSS file (using Stylance) for styling a Leptos component, and it seems to work but the styles simply don't apply. The file is read correctly by Stylance and the module is generated correctly, but on the render, the styles aren't there.
Here is my project's structure:
Cargo.toml
index.html
dist/ ...
target/ ...
src/
- lib.rs
- main.rs
- test.module.css
In main.rs
I have the following code:
use leptos::*;
use my_crate_name::*; // to import my stuff from lib.rs
pub fn main() {
mount_to_body(|| view! { <App /> });
}
#[component]
fn App() -> impl IntoView {
view! { <MyLibraryCustomComponent /> }
}
In lib.rs
:
use stylance::import_crate_style;
import_crate_style!(style, "src/test.module.css");
#[component]
pub fn MyLibraryCustomComponent() -> impl IntoView {
view! { <h1 class=style::test>"This is a title"</h1> }
}
And finally here is my test.module.css
that I wrote:
.test {
color: blue;
}
I serve the app on localhost:8080 (using trunk serve
) and with the dev console I can see that my <h1>
element has the class test-aRandomHash
. So far this is normal and intented. What's not normal is that I can't see anywhere my "color: blue" style. The <h1>
element simply doesn't have it, like it didn't exist, which is weird since Stylance has read the file and extracted the class.
I'm new to Leptos and Stylance so I've basically no idea what I'm doing. The documentation for using Stylance with Leptos is very small and basically non-existent (https://book.leptos.dev/interlude_styling.html#stylance-scoped-css-written-in-css-files).
Note that I'm not using Nightly.
EDIT: I tried using :global(.test) in the css file and it didn't change a thing. My h1 element isn't blue.
I managed to get leptos and stylance working for my client-side rendering app by following these steps:
cargo install stylance-cli
Trunk.toml
file:[[hooks]]
stage = "pre_build"
command = "stylance"
command_arguments = [".", "--output-file", "index.css"]
[watch]
ignore = ["index.css"]
index.css
in the index.html
file:<!doctype html>
<html>
<head>
<link data-trunk rel="css" href="index.css" />
</head>
<body></body>
</html>
src/main.module.scss
file:.red {
color: red;
}
src/main.rs
file:use leptos::*;
use stylance::*;
import_style!(style, "main.module.scss");
fn main() {
mount_to_body(|| view! {
<p class=style::red>"Hello, world!"</p>
})
}
trunk serve
as usualYou should see "Running stylance" in the build output and reloading should be quick because it doesn't need to recompile Rust. You will probably want to add index.css
to .gitignore
or you could locate index.css
in the target
directory if preferred. Note that the steps will likely be different if you are using server-side rendering with leptos.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With