異なるデバイスでもフォントを統一かつ綺麗で見やすいフォントを使いたい。今回はNuxt3でGoogleフォントを使う方法について記述します。
環境
- macOS 10.15.7
- Nuxt 3.2.0
- nuxtjs/google-fonts 3.0.0-1
Googleフォントを使う方法
直接googlefontのcssをインポートする方法とnuxtのライブラリを使う方法でやってみます。
headタグに追加
nuxt.config.tsに追加する方法です。Nuxt3の公式ドキュメントにもある方法です。
// https://nuxt.com/docs/api/configuration/nuxt-config
export default defineNuxtConfig({
app: {
head: {
link: [
{
rel: "preconnect",
href: "https://fonts.googleapis.com",
},
{
rel: "stylesheet",
href: "https://fonts.googleapis.com/css2?family=Inter&display=swap",
crossorigin: "",
},
],
},
},
});
引用:https://nuxt.com/docs/getting-started/seo-meta#app-head
以下のようにheadに追加されます。

ページ内でuseHeadで使っても可能でしょう。
cssの@import
@import url('https://fonts.googleapis.com/css2?family=Zen+Old+Mincho&display=swap');
@nuxtjs/google-fontsを使う
Nuxt3でGoogleフォントを使うには、@nuxtjs/google-fontsの3系を使います。2系の場合、Nuxt起動時にエラーとなってしまいます。今回は、現時点の最新版である3.0.0-1をインストールします。
yarn add --dev @nuxtjs/google-fonts@3.0.0-1
nuxt.config.tsで以下のようにするとフォントを使用できます。以下では、フォントInterを使ってみます。
// https://nuxt.com/docs/api/configuration/nuxt-config
export default defineNuxtConfig({
modules: ["@nuxtjs/google-fonts"],
googleFonts: {
families: {
Inter: true,
},
},
});
デフォルトでは、フォントがnode_modules/.cache/nuxt-google-fonts下にダウンロードされキャッシュされるようになっています。また、injectオプションがtrueのため、nuxtのページにgoogle-fontsのcssが追加されます。injectをfalseにすると自動で追加されなくなります。
$ tree node_modules/.cache/nuxt-google-fonts/
node_modules/.cache/nuxt-google-fonts/
├── css
│ └── nuxt-google-fonts.css
└── fonts
├── Inter-400-1.woff2
├── Inter-400-2.woff2
├── Inter-400-3.woff2
├── Inter-400-4.woff2
├── Inter-400-5.woff2
├── Inter-400-6.woff2
└── Inter-400-7.woff2
2 directories, 8 files
以下のようにGoogleフォントがheadに追加されていることが確認できます。



コメント