Scoped styles
<style scoped>, v-bind() in <style> and CSS modules: what Vue's server renderer writes for a component's styles.
A component with <style scoped> has its CSS rewritten by the client build to select its own elements only: .tag { … } becomes .tag[data-v-7f092129] { … }, and every element the component's template renders carries data-v-7f092129. The server has to write the same attributes, so the generated code writes them where Vue's server renderer does, and with the id the client build chose.
The id, and matching the client build
Vue's hydration does not compare attributes it does not need to patch, so a wrong id is no mismatch: the page hydrates cleanly and its styles silently fail to apply. ferrovue therefore computes the id as @vitejs/plugin-vue does, the first 8 hex digits of a SHA-256 of the .vue file's path from Vite's root, followed by its source unless only the path is hashed, and the two must be configured alike:
@vitejs/plugin-vue | ferrovue.config.json |
|---|---|
vite build with the default options | "scopeId": "filepath-source" (the default) |
features: { componentIdGenerator: "filepath" } (any mode), or the dev server | "scopeId": "filepath" |
Set viteRoot too when Vite's root is not the directory holding ferrovue.config.json: it is that root, relative to the configuration file, and the path that is hashed is the component's path from it. The Vite plugin (ferrovue/vite) compares the two when a component has scoped styles: a build in which they differ fails, and the dev server warns.
The default is the plugin's production behaviour, because the production build is the one readers get: with every option left alone, its styles apply. But plugin-vue hashes the path alone in its dev server, so with the default a page rendered during development carries other ids than the dev client's and shows unstyled. The recommended setup hashes the path alone on both sides, as the repository's examples/fullstack does:
// vite.config.ts
export default defineConfig({
plugins: [vue({ features: { componentIdGenerator: "filepath" } }), ferrovue()],
});{ "components": "client/components", "out": "src/generated", "scopeId": "filepath" }The ids are then the same in development and production, and neither they nor the generated Rust change whenever a component's source does.
What the generated code writes
The id goes on every element the component's template renders, after the element's own attributes. A child component's root also carries the id of the scoped component that renders it, as Vue's renderComponentSubTree hands it on:
<!-- client/components/Tag.vue -->
<script setup lang="ts">
defineProps<{ label: string }>();
</script>
<template>
<span class="tag">{{ label }}</span>
</template>
<style scoped>
.tag { color: teal; }
</style><!-- client/components/TagList.vue -->
<script setup lang="ts">
import Tag from "./Tag.vue";
defineProps<{ tags: string[] }>();
</script>
<template>
<ul class="tags"><li v-for="t in tags"><Tag :label="t" /></li></ul>
</template>
<style scoped>
.tags { display: flex; }
</style>With "scopeId": "filepath", Tag.vue's id is 7f092129 and TagList.vue's 2f4cdd4e. The compiler writes, for TagList:
/// Write the component's server render into `out`.
pub fn render(out: &mut String, props: &Props<'_>) {
out.reserve(
54
+ 25 * props.tags.len()
+ props.tags.iter().map(|v| v.len()).sum::<usize>()
);
out.push_str("<ul class=\"tags\" data-v-2f4cdd4e><!--[-->");
for fv_t_ref in props.tags.iter() {
let fv_t: &str = fv_t_ref;
out.push_str("<li data-v-2f4cdd4e>");
super::tag::render_scoped(out, &super::tag::Props { label: Cow::Borrowed(fv_t) }, " data-v-2f4cdd4e");
out.push_str("</li>");
}
out.push_str("<!--]--></ul>");
}
let mut out = String::new();
tag_list::render(&mut out, &tag_list::Props::new(["rust", "vue"]));
assert_eq!(
out,
concat!(
r#"<ul class="tags" data-v-2f4cdd4e><!--[-->"#,
r#"<li data-v-2f4cdd4e><span class="tag" data-v-2f4cdd4e data-v-7f092129>rust</span></li>"#,
r#"<li data-v-2f4cdd4e><span class="tag" data-v-2f4cdd4e data-v-7f092129>vue</span></li>"#,
r#"<!--]--></ul>"#,
)
);and for Tag, which a scoped parent renders, a render_scoped beside render:
/// Write the component's server render into `out`.
pub fn render(out: &mut String, props: &Props<'_>) {
render_scoped(out, props, "");
}
/// [`render`], with the scope ids a parent hands the root: ` data-v-…` each.
#[doc(hidden)]
pub fn render_scoped(out: &mut String, props: &Props<'_>, fv_attrs: &str) {
out.reserve(
41
+ props.label.len()
);
out.push_str("<span class=\"tag\"");
out.push_str(fv_attrs);
out.push_str(" data-v-7f092129>");
fv::core::escape_into(out, &props.label);
out.push_str("</span>");
}A component has a render_scoped when a parent may hand its root ids: when a scoped component renders it, when it is the root of a component that may be handed ids itself, or when it sits in slot content that may be given a slot scope id (below). fv_attrs holds those ids, each written data-v-… with its leading space; scope_attrs puts them together in the order Vue's ssrRenderAttrs writes them, keeping each once. Recursion, fragments, a root chosen by v-if, inheritAttrs: false, <Transition>, <KeepAlive>, <Teleport> and <RouterLink> are handled as Vue renders them. A component a parent also passes attributes to takes the ids inside an Attrs, after those attributes (generated_code).
render_scoped is #[doc(hidden)]: call render. A component rendered from Rust, as a page's root or an island, has no parent to hand it ids, and render writes exactly what Vue's server renderer writes for the component mounted on its own. Markup you write yourself, in a slot closure or around a component, carries only the ids it writes, so a component's scoped styles do not reach it.
Slots and :slotted()
Slot content is the parent's markup, so it carries the parent's id only. A component whose styles use :slotted(), .note :slotted(p) { … }, has them compiled to select data-v-…-s, the slot scope id, and its outlets pass that id to the content they render, which writes it onto its elements and hands it to the roots of components in it:
<!-- client/components/Note.vue -->
<script setup lang="ts">
defineProps<{ count: number }>();
</script>
<template>
<aside class="note"><slot>no note</slot><footer><slot name="footer" :count="count" /></footer></aside>
</template>
<style scoped>
.note :slotted(p) { margin: 0; }
</style>The outlets call slot_into_slotted and scoped_slot_into_slotted, the variants of slot_into and scoped_slot_into that take the slot scope id, and a scoped slot's closure takes the id as a third parameter:
/// The props `<slot name="footer">` passes the content a parent gives it, borrowed for the render.
pub struct FooterSlotProps {
pub count: i64,
}
/// A parent's content for `<slot name="footer">`, given its props and the slot scope id to write onto its elements: returns whether it wrote anything but comments.
pub type FooterSlot<'s> = dyn Fn(&mut String, &FooterSlotProps, &str) -> bool + 's;
/// What a parent puts in the slots `Note.vue` renders.
#[derive(Clone, Copy, Default)]
pub struct Slots<'s> {
/// `<slot>`
pub default: Option<fv::render::Slot<'s>>,
/// `<slot name="footer">`
pub footer: Option<&'s FooterSlot<'s>>,
}
/// Write the component's server render into `out`.
pub fn render(out: &mut String, props: &Props, fv_slots: Slots<'_>) {
out.reserve(84);
out.push_str("<aside class=\"note\" data-v-421eaec8>");
fv::render::slot_into_slotted(out, fv_slots.default, "data-v-421eaec8-s", Some(&mut |out: &mut String| {
out.push_str("no note");
}));
out.push_str("<footer data-v-421eaec8>");
fv::render::scoped_slot_into_slotted(out, fv_slots.footer, &FooterSlotProps { count: props.count }, "data-v-421eaec8-s", None);
out.push_str("</footer></aside>");
}A generated parent fills such a slot with Slot::slotted, content that is given the id. This is Notes.vue, <Note :count="2"><p>{{ text }}</p><template #footer="{ count }"><small>{{ count }} more</small></template></Note>:
/// Write the component's server render into `out`.
pub fn render(out: &mut String, props: &Props<'_>) {
out.reserve(
33
+ props.text.len()
);
super::note::render(out, &super::note::Props { count: 2i64 }, super::note::Slots {
default: Some(fv::render::Slot::slotted(&|out: &mut String, fv_slot_id: &str| -> bool {
out.push_str("<p");
out.push_str(fv_slot_id);
out.push('>');
fv::core::escape_into(out, &props.text);
out.push_str("</p>");
true
})),
footer: Some(&|out: &mut String, fv_slot_props: &super::note::FooterSlotProps, fv_slot_id_2: &str| -> bool {
out.push_str("<small");
out.push_str(fv_slot_id_2);
out.push('>');
fv::core::push_int(out, fv_slot_props.count);
out.push_str(" more</small>");
true
}),
});
}From Rust, fill the default slot with Slot::new as for any component: such content is not given the id, as static markup is not in Vue. A scoped slot's closure receives the id, data-v-…-s with its leading space, and may write it onto the elements that the component's :slotted() rules should select, or ignore it:
use ferrovue::render::Slot;
let body = |out: &mut String| out.push_str("<p>from Rust</p>");
let footer = |out: &mut String, p: ¬e::FooterSlotProps, slot_scope_id: &str| {
out.push_str("<small");
out.push_str(slot_scope_id);
out.push('>');
ferrovue::core::push_int(out, p.count);
out.push_str(" more</small>");
true
};
let mut out = String::new();
note::render(
&mut out,
¬e::Props::new(2),
note::Slots { default: Some(Slot::new(&body)), footer: Some(&footer) },
);
assert_eq!(
out,
concat!(
r#"<aside class="note" data-v-421eaec8><!--[--><p>from Rust</p><!--]-->"#,
r#"<footer data-v-421eaec8><!--[--><small data-v-421eaec8-s>2 more</small><!--]--></footer></aside>"#,
)
);Where Vue's server and client differ
Where Vue's own server render gives other ids than its client render, ferrovue writes the server's, since the server's HTML is what it promises to match:
- a
:slotted()component's slot fallback, which only the client gives the slot scope id; - a component with
inheritAttrs: falsethat is another component's root, whose root only the client gives the ids that other component inherits.
Hydration keeps the server's attributes in both cases, as it does for a page Vue rendered.
v-bind() in <style>
v-bind() in a <style> block, scoped or not, binds a CSS custom property to an expression of the component's props and setup:
<!-- client/components/Swatch.vue -->
<script setup lang="ts">
defineProps<{ color: string; size?: number }>();
</script>
<template>
<span class="swatch">{{ color }}</span>
</template>
<style scoped>
.swatch { background: v-bind(color); width: v-bind(size); }
</style>The client build rewrites the CSS to read var(--…), and Vue's server compiler writes each variable into the style of the component's root, after the root's own style and what a parent passes it. The generated code writes them where Vue's server does:
- on the root element, or on each element of a root with several, and on the elements of a root
<template v-if>; - given to a root that is a component, a
<component :is>, an async component or a<RouterLink>, as astyleattribute it falls through to; - on nothing for a root
v-for,<Transition>,<KeepAlive>or<Teleport>, where Vue's server writes none (Vue's client sets them there once it has mounted, on a page Vue rendered as on one ferrovue rendered).
A value is a string or a number, which Vue writes as ssrRenderStyle does: undefined and null as initial, an empty string as a space, and the text escaped for the attribute (" as ", < as <), nothing more. A v-bind() of a boolean, a list or an object is refused (FV1006), since Vue warns of it. The expression may be quoted, with spaces and quotes of its own: v-bind('size + "px"').
The names follow the component's id, which is computed as for a scoped component (and is computed for a component whose v-bind() is in a global <style> too), and whether plugin-vue compiles for production: a hash of the id and the expression in production, the id and the expression escaped in development. isProduction in ferrovue.config.json says which, as Vite's own setting does:
@vitejs/plugin-vue | ferrovue.config.json |
|---|---|
vite build | "isProduction": true (the default) |
| the dev server | "isProduction": false |
The Vite plugin compares both settings when a component has v-bind() in <style>: a build in which they differ fails, and the dev server warns. With "scopeId": "filepath" and "isProduction": false, Swatch renders:
/// Write the component's server render into `out`.
pub fn render(out: &mut String, props: &Props<'_>) {
out.reserve(
119
+ props.color.len()
);
out.push_str("<span class=\"swatch\" style=\"--95abae23-color:");
if props.color.is_empty() {
out.push(' ');
} else {
fv::core::escape_into(out, &props.color);
}
out.push(';');
if let Some(v) = props.size {
out.push_str("--95abae23-size:");
fv::core::push_int(out, v);
out.push(';');
} else {
out.push_str("--95abae23-size:initial;");
}
out.push_str("\" data-v-95abae23>");
fv::core::escape_into(out, &props.color);
out.push_str("</span>");
}and, compiled for production, the same with --v52530d6a and --v3881b919 for the names.
Vue's client checks the variables as it hydrates, and itself reports a mismatch for a value that is empty or blank, or that holds a ;, which it reads back otherwise than its server wrote it. A <Suspense> root's content carries the variables on the server, where the client does not look for them, which it reports too. ferrovue writes what Vue's server writes in each case.
CSS modules
A <style module> block's classes are renamed by the bundler, and a template reads their new names from $style (<style module="name"> from name, and useCssModule() or useCssModule("name") in setup):
<!-- client/components/Toggle.vue -->
<script setup lang="ts">
defineProps<{ label: string; active: boolean }>();
</script>
<template>
<button :class="[$style.button, { [$style.active]: active }]">{{ label }}</button>
</template>
<style module>
.button { padding: 0 1em; }
.active { font-weight: bold; }
</style>Vite names them by css.modules.generateScopedName, through postcss-modules. Left unset, the name holds a hash of the CSS and a line number, which changes as the block does; ferrovue computes the names only when the pattern is set, in Vite and as cssModules in ferrovue.config.json alike, and refuses <style module> otherwise (FV1005):
// vite.config.ts
export default defineConfig({
css: { modules: { generateScopedName: "[local]_[hash:base64:5]" } },
plugins: [vue(), ferrovue()],
});{ "components": "client/components", "out": "src/generated", "cssModules": { "generateScopedName": "[local]_[hash:base64:5]" } }Toggle then renders <button class="button_cmjmr active_Sa5O5">: each name is a constant in the generated code, and a class the module does not have is undefined, as in Vue.
The pattern is any string postcss-modules takes, and ferrovue computes it with the same libraries:
| Part | What it is |
|---|---|
[local] | the class as written |
[hash:base64:5] | a hash of hashPrefix, the module's path from the directory Vite runs in, and the class (xxhash64 by default; [md5:hash:hex:8] and the like choose another hash and digest) |
[name] | the module's file name as Vite sees it, the component's with plugin-vue's query: Toggle-vue-vue-type-style-index-0-lang-module |
[path], [folder], [ext] | the module's directory from the directory Vite runs in, its last folder, and css |
A hash and [path] take the module's path from the directory Vite runs in, its working directory: set cssModules.context to it, relative to ferrovue.config.json, when it is not viteRoot. The path holds the component's id for a <style module scoped>, so its names follow scopeId too. cssModules.hashPrefix is Vite's css.modules.hashPrefix.
The Vite plugin compares the two when a component has <style module>, and fails a build in which Vite would name the classes otherwise: another pattern, another hashPrefix, another working directory for a pattern that hashes the path, a localsConvention (which renames the classes a template reads), global scoping, or css.transformer: "lightningcss", which names them by rules of its own.
ferrovue reads the module as written in the component, in plain CSS, as Vite does before plugin-vue compiles it. It refuses (FV1014) a module in another file (src), one a preprocessor compiles (lang="scss"), and one that imports from another file (composes: x from "./a.css", @value x from "./a.css"). A PostCSS plugin of the project's runs before postcss-modules in Vite; one that adds or renames classes changes names ferrovue does not see.
What is refused
<style module>withoutcssModulesin the configuration, and the modules above;v-bind()in<style>of a value that is not a string or a number;<RouterView>in a component with<style scoped>, which would give the page that component's id;- since vue-router renders a link from virtual nodes, a
<slot>inside a<RouterLink>that takes scope ids, and an element inside a<RouterLink>in slot content given a:slotted()id.
A global <style> block, beside a scoped one or alone, needs nothing from the server.