Access Next.js Optimized Fonts Dynamically
Asked Answered
A

0

7

I am currently using a json file to determine which fonts to import for my Next.js site. Next.js has optimized google fonts you can import locally which has better performance then doing a google import myself. However the way you import these font classes seems to require you to know the font being used.

import { Inter, Lora, Lato, Abril_Fatface } from 'next/font/google'

I am trying to figure out if there is a way I can dynamically import the function based on which font is passed through the json file.

I tried importing all of the fonts

import * as exports from 'next/font/google'
const inter = exports.Inter({ subsets: ['latin'] })

But I receive the error of "Font loaders can't have namespace imports"

Is there any way around having to import every single font and create variables for all of them when I only will need to use the one determined by the json.

Here is the code currently working with importing each one

import {
    Inter,
    Lora,
    Abril_Fatface,
    Lato,
    Alegreya_Sans,
    Alegreya_Sans_SC,
    Amatic_SC,
    Anton,
    Artifika,
    
} from 'next/font/google'

const inter = Inter({ subsets: ['latin'] })

const lato = Lato({ weight: ['300', '400', '700'], style: ['normal', 'italic'], subsets: ['latin'], variable: '--lato' })
const lora = Lora({ subsets: ['latin'], variable: '--lora' })
const abril_flatface = Abril_Fatface({ weight: ['400'], style: ['normal'], subsets: ['latin'], variable: '--abril' })

const alegreya_sans = Alegreya_Sans({ weight: ['300', '400', '700'], subsets: ['latin'] })
const alegreya_sans_sc = Alegreya_Sans_SC({ weight: ['300', '400', '700'], subsets: ['latin'] })
const amatic_sC = Amatic_SC({ weight: ['400', '700'], subsets: ['latin'] })

const anton = Anton({ weight: ['400'], subsets: ['latin'] })
const artifika = Artifika({ weight: ['400'], subsets: ['latin'] })
Alfy answered 13/3, 2023 at 18:0 Comment(1)
I have the same feature (get a json that defines the page font). did you get a solution?Visigoth

© 2022 - 2024 — McMap. All rights reserved.