Skip to main content

Use Google Fonts in Docusaurus

一、一般 css import

1.在 html head import


<head>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Sofia">
<style>
body {
font-family: "Sofia", sans-serif;
}
</style>
</head>

2.在 css import

scr/css/custom.css
@import url("https://fonts.googleapis.com/css2?family=Caveat:wght@500&display=swap");
// css選擇器選使用範圍
nav .navbar__items {
font-size: 30px;
font-family: Caveat;
}

//如果多個font import
@import url("https://fonts.googleapis.com/css2?family=Caveat:wght@500&display=swap");
@import url("https://fonts.googleapis.com/css2?family=Noto+Sans+TC&display=swap");

// css 選擇標示用逗號分隔
html {
font-family: Noto Sans TC, sans-serif;
}

二、在 docusaurus 使用

1.在 html head import

這個方法相當於一般 css 使用在 head 打 link,只是寫在設定檔內,會於編譯後產生在 index.html 的 head 裡面

<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Noto+Sans+TC&amp;display=swap">
docusaurus.config.js
        theme: {
customCss: require.resolve("./src/css/custom.css"),
},
},
],
],
stylesheets: [
{
rel: "preconnect",
href: "https://fonts.googleapis.com",
},
{
rel: "preconnect",
href: "https://fonts.gstatic.com",
crossorigin: "anonymous",
},
{
rel: "stylesheet",
href: "https://fonts.googleapis.com/css2?family=Noto+Sans+TC:wght@400;700;900&display=swap",
},
],

2.在 css import

做法同一般 css import

scr/css/custom.css
@import url("https://fonts.googleapis.com/css2?family=Caveat:wght@500&display=swap");
// css選擇器選使用範圍
nav .navbar__items {
font-size: 30px;
font-family: Caveat;
}

//如果多個font import
@import url("https://fonts.googleapis.com/css2?family=Caveat:wght@500&display=swap");
@import url("https://fonts.googleapis.com/css2?family=Noto+Sans+TC&display=swap");

// css 選擇標示用逗號分隔
html {
font-family: Noto Sans TC, sans-serif;
}

三、比較兩種方法差異

一般css import

malta_street png

link import

malta_street png
tip

寫法上來說,直接在 custom css import 比較方便的,傳送的大小跟時間也是沒啥差, 所以目前都用 css import 的方法。有寫錯麻煩指正~

四、 參考資料