Set up Master CSS in Svelte
Guide to setting up Master CSS in your Svelte project.
Master CSS Progressive Rendering scans the rendered HTML ahead of time, server-side or at build time, generates the corresponding CSS rules for each page, and defer loads the runtime engine to keep track of the dynamic class names.
Faster page loading
Non-rendering-blocking internal CSS and defer loading
Fully automatic
Capture any program-generated class names
CSS encapsulation
Only ship the page-used CSS instead of the whole site
Quick start
Clone the example
Copy-paste the commands to quickly start using the https://svelte.pr.rc.css.master.co example.
You can skip all installation steps.
npm create @master/css@rc <project> --example sveltecd <project>npm run dev
Installation
Create a project
If you don't have a Svelte project, create one first. It's recommended to refer to Svelte Kit.
npm create svelte@latest <project>cd <project>npm install
Initialize configuration file
Run the command to create a configuration file master.css.ts.
npm create @master/css@rc
Install Master CSS
Install Master CSS Svelte into your project via package managers.
npm i @master/css.svelte@rc @master/css-server@rc
Allow configuration file
Add ./master.css.ts
to the server.fs.allow
section in vite.config.ts
to be allowed by the server file system.
Accessing files outside this directory list that aren't imported from an allowed file will result in a 403.
import { sveltekit } from '@sveltejs/kit/vite'import { defineConfig } from 'vite'export default defineConfig({ plugins: [sveltekit()], server: { fs: { allow: ['./master.css.ts'] } } })
Set up CSS runtime engine
Register Master CSS and provide instance context in src/routes/+layout.svelte
:
- Import
CSSRuntimeProvider
- Import
config
@master/css.svelte
and master.css.ts
will not be included in the page's initial JavaScript bundle.
<script lang="ts"> import CSSRuntimeProvider from "@master/css.svelte"; import config from "../../master.css";[!code ++] */ </script><CSSRuntimeProvider config={config}> <slot /></CSSRuntimeProvider>
Set up Master CSS renderer
Create a src/hooks.server.ts
and use the render()
to scan the rendered HTML of the Svelte pages, extract class names, generate CSS rules, and inject the CSS text.
import { render } from '@master/css-server' import config from '../master.css' /** @type {import('@sveltejs/kit').Handle} */export async function handle({ event, resolve }) { return await resolve(event, { transformPageChunk: ({ html }) => render(html, config).html })}
Launch server
Run npm run dev -- --open
to start your Svelte development server
npm run dev -- --open
Start using Master CSS
Now style your first element using Master CSS syntax!
<h1 class="font:40 fg:blue font:heavy italic m:12x text:center">Hello World</h1>
Open your browser to watch the changes.