懂杯帝 Blog【非教育业相关内容】
切换菜单
代码高亮分享

代码高亮分享

代码高亮的使用方法

标题

分享来源

console.log("hello world");

代码标题

方式一:

my-test-file.js
console.log("Title attribute example");

方式二:

src/content/index.html
<div>File name comment example</div>

终端帧

PowerShell terminal example
Write-Output "This one has a title!"

部署代码高亮并适配暗夜模式

使用组件

Expressive Code

安装

npx astro add astro-expressive-code

配置

astro.config.mjs
//代码高亮
import astroExpressiveCode from "astro-expressive-code";
markdown: {
// 关键:关掉 Astro 默认 Shiki 高亮,否则你看到的仍是 Shiki 输出
syntaxHighlight: false,
},
integrations: [
//代码高亮,基于渲染顺序,需要在mdx前
astroExpressiveCode(),
mdx(),
...

配置文件

这里放置代码高亮相关的配置,文件创建到根目录下

ec.config.mjs
//代码高亮相关配置
import { defineEcConfig } from "astro-expressive-code";
import { pluginLineNumbers } from "@expressive-code/plugin-line-numbers";
export default defineEcConfig({
//主题
themes: ["github-dark-default", "gruvbox-dark-hard"],
useDarkModeMediaQuery: false, //禁用自动媒体查询切换
themeCssRoot: "html", //指定主题CSS变量的作用域根元素
//暗夜模式切换
themeCssSelector: (theme) =>
theme.type === "dark" ? ".dark" : ":not(.dark)",
//展示行号
plugins: [pluginLineNumbers()],
});

主题部分,可通过以下命令,找到所有可用主题

查看当前支持的主题

Terminal window
node -e "const { bundledThemes } = require('shiki'); console.log(Object.keys(bundledThemes))"
## 前50个
node -e "const { bundledThemes } = require('shiki'); console.log(Object.keys(bundledThemes).slice(0,50))"