You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Sanity.io代码输入添加高亮行输入字段?

Solution: Add highlightedLines to Sanity Code Blocks

Yep, you're on the right track—you do need to create a custom code type instead of trying to modify Sanity's built-in code type directly. Here's how to fix this step by step:

1. Create a Custom Code Block Schema

Sanity's built-in code type is a pre-defined object with its own locked-in fields. To add highlightedLines, make a new custom schema file (e.g., schemas/customCode.js) that replicates the core functionality of the built-in code block plus your new field:

// schemas/customCode.js
export default {
  title: "Code Block",
  name: "customCode",
  type: "object",
  fields: [
    // Replicate built-in code block fields
    {
      title: "Language",
      name: "language",
      type: "string",
      options: {
        list: [
          { title: "JavaScript", value: "js" },
          { title: "HTML", value: "html" },
          { title: "CSS", value: "css" },
          // Add any other languages you need here
        ],
        layout: "dropdown"
      }
    },
    // Your new highlightedLines field
    {
      title: "Highlighted Lines",
      name: "highlightedLines",
      type: "array",
      of: [{ type: "number" }],
      description: "Enter line numbers to highlight (e.g., [1, 3])"
    },
    {
      title: "Code",
      name: "code",
      type: "text",
      validation: Rule => Rule.required()
    },
    {
      title: "Filename",
      name: "filename",
      type: "string"
    }
  ],
  // Keep the built-in filename display option
  options: {
    withFilename: true
  }
};

2. Update Your Block Content to Use the Custom Type

Now replace the reference to Sanity's built-in code type in blockContent.js with your new custom type:

// schemas/blockContent.js
import customCode from './customCode'; // Import your custom schema

export default {
  title: "Block Content",
  name: "blockContent",
  type: "array",
  of: [
    // ... keep your existing block types (paragraph, image, etc.)
    { 
      type: "image", 
      options: { hotspot: true }, 
    },
    // Replace the built-in code type with your custom one
    {
      type: customCode.name // Or just write "customCode" directly
    }
  ]
};

Why Your Original Approach Failed

Sanity prevents overriding fields on pre-defined object subtypes (like the built-in code type) because those types have their own fixed schema configurations. The only safe way to extend them is to create a custom object type that duplicates their core fields and adds your new ones.

Once you set this up, you'll be able to use the highlightedLines field in your Studio exactly like the example from the npm page!

内容的提问来源于stack exchange,提问作者HynekS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 15:07:51