如何在Leptos中使用Stylance?样式不生效问题求助
问题:Stylance作用域CSS在Leptos组件中样式未生效
我尝试使用Stylance的作用域CSS文件为Leptos组件设置样式,文件已被Stylance正确读取且模块生成正常,但渲染时样式未生效。
项目结构
Cargo.toml index.html dist/ ... target/ ... src/ - lib.rs - main.rs - test.module.css
相关代码
main.rs
use leptos::*; use my_crate_name::*; // 从lib.rs导入自定义内容 pub fn main() { mount_to_body(|| view! { <App /> }); } #[component] fn App() -> impl IntoView { view! { <MyLibraryCustomComponent /> } }
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> } }
test.module.css
.test { color: blue; }
现象
使用trunk serve在localhost:8080运行应用,开发者控制台显示<h1>元素带有test-aRandomHash类,但color: blue样式未生效。尝试:global(.test)也无效果。
解决方案
配置Trunk与Stylance的构建钩子
在项目根目录创建或修改Trunk.toml,添加Stylance构建钩子,确保Trunk构建时调用Stylance处理CSS模块:[[hooks]] stage = "build" command = "cargo" args = ["stylance", "build"]注入样式文件到页面
修改lib.rs,通过Leptos元上下文注入编译后的样式表:use leptos::*; use stylance::import_crate_style; import_crate_style!(style, "src/test.module.css"); #[component] pub fn MyLibraryCustomComponent() -> impl IntoView { provide_meta_context(); view! { <Stylesheet href="/style.css" /> <h1 class=style::test>"This is a title"</h1> } }Stylance默认将编译后的样式输出到
dist/style.css,确保路径与实际输出一致。验证Stylance编译结果
手动执行cargo stylance build,检查dist目录下的style.css,确认包含类似.test-aRandomHash { color: blue; }的规则。补充Trunk资源配置
若Trunk未正确识别样式文件,在Trunk.toml中添加资源规则:[[assets]] path = "src/test.module.css" target = "style.css"
内容的提问来源于stack exchange,提问作者ThomasG2201
相关产品推荐
相关产品推荐

