如何为Sanity.io代码输入添加高亮行输入字段?
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

