Vanilla Extract is a new "CSS in JS" library that offers type safety, good theming support, and plenty of extensions, making it an exciting alternative to existing solutions such as Styled Components.
While modern CSS offers designers and developers a much broader set of tools to apply sophisticated designs to web applications, the core concept of cascading style sheets, vendor prefixes, etc. leads many developers to use alternative "CSS in JS" libraries that simplify the development process.
Vanilla Extract is one such library that offers a modern take on the process.
When using Vanilla Extract, CSS Styles are placed within .css.ts files; this separates the design from the code and leverages TypeScript to provide type safety.
This also enables Vanilla Extract to generate the CSS at build time, which offers improved performance compared to other "CSS in JS" libraries like Styled Components, which evaluated them on runtime.
To get started with Vanilla extract, install the npm package using:
npm install @vanilla-extract/css
and follow the integration guide to integrate it with your bundler of choice.
Creating styles works similarly to other CSS in JS libraries and allows developers to create either globally or locally scoped styles.
import { style, globalStyle } from '@vanilla-extract/css';
export const scopedStyle = style({ backgroundColor: #000000; });
globalStyle('body', { backgroundColor: #ffffff; });
Theming is an integral part of Vanilla extract and, at its core, is simply a set of helpers around CSS variables.
Creating a theme is a two-part process. First, developers define the theme structure using createThemeContract, after which they can create multiple themes that adhere to the same structure.
Since the contracts are only used to define the structure, their property values are not used and are usually set to null.
import { createThemeContract, createTheme, style } from '@vanilla-extract/css';
export const vars = createThemeContract({
primaryColor: null,
secondaryColor: null,
});
export const themeA = createTheme(vars, {
primaryColor: #efefef,
secondaryColor: #fefefe,
});
Vanilla extract also supports global themes using the createGlobalTheme function.
import { createGlobalTheme } from "@vanilla-extract/css";
const globalTheme = createGlobalTheme("#app", {
fonts: {
header: "Times, Times New Roman, serif",
body: "arial"
},
});
Since all themes are just JavasScript objects, they can be combined using the spread operator.
export const vars = { ...globalTheme , themeA};
Finally, global styles and themes are applied automatically by Vanilla Extract. Scoped themes and styles return a class that is used within the TSX template.
const App = ({ children }) => {
return (
<div id="app" className={themeA}>
{children}
</div>
);
};
Vanilla Extract is open-source software available under the MIT license. Contributions are welcome via the Vanilla Extract GitHub repository.