當我們在 Astro MDX 中寫一段程式碼,那麼它預設會長這樣:
這個 code block 實在長的太陽春了,我會想對他做這些設定:
我們可以先透過 Astro 官方推薦的插件做基本的處理,再加一些客製化的設定。
astro-expressive-code 是一個整合 expressive code 和 Astro 的套件。
使用 Astro CLI(推薦)
# When using npmnpx astro add astro-expressive-code
# When using pnpmpnpm astro add astro-expressive-code
# When using yarnyarn astro add astro-expressive-code也可以自己安裝依賴,並將其引入設定檔中
# When using npmnpm install astro-expressive-code
# When using pnpmpnpm install astro-expressive-code
# When using yarnyarn add astro-expressive-codeimport { defineConfig } from 'astro/config'import mdx from '@astrojs/mdx'import astroExpressiveCode from 'astro-expressive-code'
// 在 https://expressive-code.com/guides/themes/ 挑選想要的主題const astroExpressiveCodeOptions = { theme: 'min-light',}
export default defineConfig({ // 注意:astroExpressiveCode() 需置於 mdx() 的前方避免報錯 integrations: [astroExpressiveCode(), mdx()],})設定完成後可以看到 code block 有如我們想要的那樣加上了 padding 和右上角的複製按鈕。
astro-expressive-code 還提供了一些其他功能,像是標記特定行數、顯示 diff 等等,詳情可以參考文件。
我們可以將想使用的主題設定傳進 astroExpressiveCode 裡,就可以達成像本文的 code block 一樣的效果啦!
const astroExpressiveCodeOptions = { theme: 'rose-pine-dawn',}export default defineConfig({ integrations: [astroExpressiveCode(astroExpressiveCodeOptions), mdx()],})除了主題之外,你也可以設定其他樣式像是反白的顏色等等,詳情可以參考文件。