最近用 Next.js 開發網站時,嘗試使用 Markdown 作為文章來源,在開發上方便許多,一來可以不用後端也可以建立小型的前端文章資料庫;二來是編輯時很直觀,可以不用寫成 HTML 標籤,還可以用 VScode 預覽。
然而將 Markdown 的文章引入以後,有的 CSS 框架會預設把所有標籤樣式移除。在 Next.js 中,如何替 Markdown 文章建立適當的樣式呢?以下會提供兩種方法。
## github-markdown-css
來源:[npm - github-markdown-css](https://www.npmjs.com/package/github-markdown-css/v/4.0.0)
專案中引入套件:
```
npm install github-markdown-css
```
接著在想要用的頁面中引入 css,想要引入的元件上加上 `markdown-body` 的 className 就可以了。
```javascript!
import 'github-markdown-css/github-markdown.css';
export default function Article({ contentHtml }) {
return (
<article
className="markdown-body"
dangerouslySetInnerHTML={{ __html: contentHtml }}
/>
);
}
```
看起來會跟 GitHub 的 README 文件檔看起來幾乎一樣,熟悉他們文件檔的會看得很習慣。
不過有個缺點,是他們的 h1 與 h2 都有底線的樣式,如果兩者上下並排時會因太多底線閱讀起來不連貫的感覺。所以我後來找到 tailwind 本身就有出類似的工具包,我個人覺得看起來更美觀。
## tailwindcss-typography
來源:[GitHub - tailwindcss-typography](https://github.com/tailwindlabs/tailwindcss-typography)
安裝套件:
```
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init
```
然後到 tailwind.config.js 中調整設定(如果缺這個檔案就自己手動新增)。
```javascript
module.exports = {
content: [
'./app/**/*.{js,ts,jsx,tsx}'
],
plugins: [require('@tailwindcss/typography')],
};
```
接著在想要用的頁面中引入 css,想要引入的元件上加上 `prose` 的 className 就可以了。
```javascript!
export default function Article({ contentHtml }) {
return (
<article
className="prose"
dangerouslySetInnerHTML={{ __html: contentHtml }}
/>
);
}
```
### 補充:inline code 的樣式不是方塊!
在 tailwind 的這個版本中,inline code 的樣式不是一個方框,而是用 `` 反引號的方式顯示。個人覺得跟平常的閱讀習慣有差異,所以後來寫了一個樣式去蓋掉它。
```css!
.prose p code {
background-color: #818b981f;
padding: 0.2em 0.4em;
border-radius: 0.25rem;
font-size: 0.875em;
font-family: var(--fontStack-monospace, ui-monospace, SFMono-Regular, SF Mono, Menlo, Consolas, Liberation Mono, monospace);
}
.prose p code::before,
.prose p code::after {
content: none;
}
```
這樣就能讓 inline code 更清處,也符合平常的閱讀習慣。
### 參考資料
- [npm - github-markdown-css](https://www.npmjs.com/package/github-markdown-css/v/4.0.0)
- [GitHub - tailwindcss-typography](https://github.com/tailwindlabs/tailwindcss-typography)
- [Medium - Building a markdown-powered Page in Next.js and style it with Tailwind](https://medium.com/@igorkhomenko/building-a-markdown-powered-page-in-next-js-and-style-it-with-tailwind-0a3bbf128649)