Loading Custom Fonts
Missed my talk? More info in the slide notes ;)
But what if:
…???
Styled Components
Storybook
React
@font-face
Web Font File Formats
TLDR: Stick to .otf, .ttf and .woff/.woff2
Conversion Tools: Cloud Convert , FontForge, Transfonter
Keep it organized 🛢️
😩😩😩
Make the compiler happy
// typings/fonts.d.ts
declare module '*.woff2';
declare module '*.woff';
declare module '*.ttf';
declare module '*.otf';
// tsconfig.json
{
"compilerOptions": {
...
"include": [
"typings",
"*.d.ts"
]
}
// src/tokens/fonts.ts
import { ProximaNovaRegularOtf,ProximaNovaRegularTtf,ProximaNovaRegularWoff, ProximaNovaRegularWoff2 } from "../fonts";
const mainFont = "Proxima Nova";
const fallbackFontStack = "Helvetica Neue, Arial, sans-serif";
export const fontFamily = {
regular: `${mainFont}`,
bold: `${mainFont} Bold`,
};
export const fonts = {
heading: `${fontFamily.bold}, ${fallbackFontStack}`,
body: `${fontFamily.regular}, ${fallbackFontStack}`,
};
// tokens/fonts.ts
export const globalFonts = `
@font-face {
font-family: 'Proxima Nova';
src: url(${ProximaNovaRegularWoff2}) format('woff2'),
url(${ProximaNovaRegularWoff}) format('woff'),
url(${ProximaNovaRegularOtf}) format('opentype'),
url(${ProximaNovaRegularTtf}) format('ttf');
font-weight: 400;
font-style: normal;
font-display: optional;
fallback: ${fallbackFontStack};
}`;
Prevent layout shifts and Flash of Unstyled Text
What about in Storybook?
// .storybook/preview-head.html
<link
rel="preload"
href="./static/media/ProximaNova-Regular.woff2"
as="font"
type="font/woff2"
crossorigin
/>
...
<style type="text/css">
@font-face {
font-family: "Proxima Nova";
font-style: normal;
font-weight: 400;
src: /* Modern Browsers */ url("./static/media/ProximaNova-Regular.woff2") format("woff2"),
url("./static/media/ProximaNova-Regular.woff") format("woff"),
url("./static/media/ProximaNova-Regular.otf") format("opentype"),
/* Safari, Android, iOS */ url("./static/media/ProximaNova-Regular.ttf")
format("truetype");
font-display: optional;
}}
</style>
import { createGlobalStyle } from "styled-components";
import { globalFonts } from "./fonts";
const GlobalStyle = createGlobalStyle`${globalFonts}`;
function App() {
return (
<>
<GlobalStyle />
<div className="App">
<section>
<Heading as="h1">Browser default size with H1 tag</Heading>
<Heading as="h2">Browser default size H2 tag</Heading>
<Heading as="h3">Browser default size H3 tag</Heading>
</section>
</div>
</>);}
Inject the Global Styles
Quarter of a second on Chrome with .otf!
167 ms with .woff2 on Chrome
Throttled 3G: 5 seconds on Chrome with woff2