跳转到内容
Filters

    代码

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

    预览
    example.md
    ## 欢迎
    来自 **宇宙** 的问候!
    import { Code } from '@astrojs/starlight/components';

    使用 <Code> 组件的渲染能将代码语法高亮,例如在展示从外部源获取的代码时。

    有关如何使用 <Code> 组件和可用属性的完整列表信息,请参阅 Expressive Code “代码组件” 文档

    import { Code } from '@astrojs/starlight/components';
    export const exampleCode = `console.log('这可能来自文件或 CMS!');`;
    export const fileName = 'example.js';
    export const highlights = ['文件', 'CMS'];
    <Code code={exampleCode} lang="js" title={fileName} mark={highlights} />
    预览
    example.js
    console.log('这可能来自文件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 Component” 文档 中记录的所有 props。