代码
<Code>
组件可以渲染带语法高亮的代码。当无法使用 Markdown 代码块时(例如,渲染来自文件、数据库或 API 等外部来源的数据),它会非常有用。
## 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} />
{% code code="console.log('This could come from a file or CMS!');" lang="js" title="example.js" meta="'file' 'CMS'" /%}
console.log('This could come from a file or CMS!');
显示导入的代码
章节:“显示导入的代码”在 MDX 文件和 Astro 组件中,使用 Vite 的 ?raw
导入后缀可将任何代码文件作为字符串导入。然后,你可以将此导入的字符串传递给 <Code>
组件,以将其包含在页面上。
import { Code } from '@astrojs/starlight/components';import importedCode from '/tsconfig.json?raw';
<Code code={importedCode} lang="json" title="tsconfig.json" />
{ "extends": "astro/tsconfigs/strict", "include": [".astro/types.d.ts", "**/*"], "exclude": ["dist"]}
<Code>
属性
章节:“<Code> 属性”实现: Code.astro
<Code>
组件接受 Expressive Code “Code 组件”文档中说明的所有属性。