跳转到内容

CodeBlock 代码块

带文件名头与复制按钮的代码框。

codeBlock() 渲染带框代码图,可选文件名头与 ghost 复制按钮。复制按钮由 运行时接线([data-cpd-copy])。

文件名头
src/lib/ui/tokens.ts
export const LAYOUT = {
  sidebarWidth: 256,
  tocWidth: 256,
  pageMaxWidth: 800,
} as const;
codeBlock({
filename: 'src/lib/ui/tokens.ts',
lang: 'ts',
code: 'export const LAYOUT = {\n sidebarWidth: 256,\n tocWidth: 256,\n pageMaxWidth: 800,\n} as const;\n',
});
裸代码
Bash
bun install
bun run dev
codeBlock({
lang: 'bash',
code: 'bun install\nbun run dev\n',
});

传入 tabs 可渲染多文件 Snippet:头部按文件渲染一个 标签;复制按钮复制当前激活标签的内容。

带标签的 Snippet
export function renderDrawer(options) {
  // ...
}
export function initDrawers(root) {
  // ...
}
codeBlock({
lang: 'ts',
tabs: [
{ label: 'drawer.ts', code: 'export function renderDrawer(options) {\n // ...\n}\n' },
{ label: 'runtime.ts', code: 'export function initDrawers(root) {\n // ...\n}\n' },
],
});
参数类型默认值说明
codestring代码文本(省略 tabs 时必填)。
filenamestring''文件名头——同时启用复制按钮。
langstring''语言提示类(language-<lang>),不做语法高亮。
tabsCodeBlockTab[]多文件 Snippet:每文件 { label, code };头部渲染标签,复制按钮复制当前标签。
  • 构建器会转义 code——原始标记永不执行。
  • Kit 不内置语法高亮;真实文档页改用 astro-expressive-code 块(样式已对齐)。
  • 复制使用 navigator.clipboard,带 execCommand('copy') 回退。