跳转到内容

代码

<Code> 组件可以渲染带语法高亮的代码。当无法使用 Markdown 代码块时(例如,渲染来自文件、数据库或 API 等外部来源的数据),它会非常有用。

预览
example.md
## Welcome
Hello from **space**!
import { Code } from '@astrojs/starlight/components';

使用 <Code> 组件来渲染带语法高亮的代码,例如当显示从外部源获取的代码时。

请参阅 Expressive Code “Code 组件”文档,以获取如何使用 <Code> 组件的完整说明以及可用属性的列表。

import { Code } from '@astrojs/starlight/components';
export const exampleCode = `console.log('This could come from a file or CMS!');`;
export const fileName = 'example.js';
export const highlights = ['file', 'CMS'];
<Code code={exampleCode} lang="js" title={fileName} mark={highlights} />
预览
example.js
console.log('This could come from a file or CMS!');

在 MDX 文件和 Astro 组件中,使用 Vite 的 ?raw 导入后缀可将任何代码文件作为字符串导入。然后,你可以将此导入的字符串传递给 <Code> 组件,以将其包含在页面上。

src/content/docs/example.mdx
import { Code } from '@astrojs/starlight/components';
import importedCode from '/tsconfig.json?raw';
<Code code={importedCode} lang="json" title="tsconfig.json" />
预览
tsconfig.json
{
"extends": "astro/tsconfigs/strict",
"include": [".astro/types.d.ts", "**/*"],
"exclude": ["dist"]
}

实现: Code.astro

<Code> 组件接受 Expressive Code “Code 组件”文档中说明的所有属性。