Skip to content

Instantly share code, notes, and snippets.

@mkbctrl
Created April 4, 2020 19:28
Show Gist options
  • Save mkbctrl/31c5c606f240e579b808f337581f7220 to your computer and use it in GitHub Desktop.
Save mkbctrl/31c5c606f240e579b808f337581f7220 to your computer and use it in GitHub Desktop.
[Next.js] [Typescript] Add internal ( self hosted ) font file with FontFaceObserver
// #### APP.TSX ####
// /src/pages/_app.tsx
import App from 'next/app'
import { loadFontPrimary } from '@utils/fontLoadObserver'
import FontFace from '@styles/FontFace'
import BaseStyles from '@styles/Base'
import { Reset } from 'styled-reset'
import VContainer from '@components/VContainer/VContainer'
class MyApp extends App {
componentDidMount() {
loadFontPrimary()
}
render() {
const { Component, pageProps } = this.props
return (
<VContainer>
<FontFace />
<Reset />
<BaseStyles />
<Component {...pageProps} />
</VContainer>
)
}
}
export default MyApp
// #### FONTFACE.TS ####
// /src/styles/FontFace.ts
import { createGlobalStyle } from 'styled-components'
const FontFace = createGlobalStyle`
@font-face {
font-family: Axiforma-Medium;
src: local('Axiforma Medium'), local('Axiforma-Medium'),
url('../../public/fonts/Axiforma/Axiforma-Medium.eot?#iefix') format('embedded-opentype'),
url('/fonts/Axiforma/Axiforma-Medium.woff2') format('woff2'),
url('/fonts/Axiforma/Axiforma-Medium.woff') format('woff'),
url('/fonts/Axiforma/Axiforma-Medium.ttf') format('truetype');
font-weight: 500;
font-style: normal;
}
@font-face {
font-family: Axiforma-ExtraBold;
src: local('Axiforma ExtraBold'), local('Axiforma-ExtraBold'),
url('/fonts/Axiforma/Axiforma-ExtraBold.eot?#iefix') format('embedded-opentype'),
url('/fonts/Axiforma/Axiforma-ExtraBold.woff2') format('woff2'),
url('/fonts/Axiforma/Axiforma-ExtraBold.woff') format('woff'),
url('/fonts/Axiforma/Axiforma-ExtraBold.ttf') format('truetype');
font-weight: 800;
font-style: normal;
}
`
export default FontFace
// #### FONTLOADOBSERVER.ts ####
// /src/utils/fontLoadObserver.ts
import FontFaceObserver from 'fontfaceobserver'
export const loadFontPrimary = () => {
const fontMedium = new FontFaceObserver('Axiforma-Medium', {
weight: 500
})
const fontExtraBold = new FontFaceObserver('Axiforma-ExtraBold', {
weight: 800
})
Promise.all([fontMedium.load(null, 10000), fontExtraBold.load(null, 10000)])
.then((response) => {
if (process.env.NODE_ENV === 'development') return console.log(response)
})
.catch((error) => Error(error))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment