Set up Master CSS in Rails
Guide to setting up Master CSS in Ruby on Rails views.
Use Vite runtime rendering when Rails owns the page lifecycle. Rails renders ERB views, while the Vite-built Master CSS runtime generates class rules in the browser as pages and Turbo updates appear.
Create a project
If you do not have a Rails project, create one first.
rails new my-appcd my-appnpm init -yInstall Vite and Master CSS
Install Vite and the Master CSS Vite integration in the Rails project root.
npm install -D vite @master/css.vite@rcConfigure Vite
Build the runtime entry and base stylesheet into public/assets.
import { defineConfig } from 'vite'import masterCSS from '@master/css.vite'export default defineConfig({ plugins: [ masterCSS({ mode: 'runtime', injectRuntime: false }) ], build: { outDir: 'public/assets', emptyOutDir: true, rollupOptions: { input: 'app/frontend/main.ts', output: { entryFileNames: 'app.js', assetFileNames: 'app[extname]' } } }})Create the asset entry
Import the Vite-managed runtime and the Master CSS stylesheet.
import '@master/css.vite/runtime'import './app.css'@import "@master/css";Load the assets
Reference the Vite output from the Rails application layout. Add hidden so the runtime can avoid a flash of unstyled content before it injects class rules.
<html lang="en" hidden><head> <%= stylesheet_link_tag "/assets/app.css" %></head><body> <%= yield %> <%= javascript_include_tag "/assets/app.js", type: "module" %></body></html>Add build scripts
Build or watch the frontend assets beside the Rails server.
{ "scripts": { "build:assets": "vite build", "watch:assets": "vite build --watch" }}Hello world
Now style your first ERB view using Master CSS syntax.
Hello World
<h1 class="m:2xl italic font:5xl font:heavy text:neutral"> Hello World</h1>Use Rails static rendering when ERB class strings are complete at build time and you want a generated CSS asset.