如何在Sanity架构中导入并共享自定义Portable Text编辑器?
解决Sanity共享富文本编辑器Schema的问题
首先,核心问题出在共享编辑器的导出格式或导入使用方式上,以下是具体解决步骤:
1. 确保共享编辑器文件的导出格式正确
假设你之前直接写在Schema里能正常运行的of字段内容是类似这样的数组结构:
of: [ { type: 'block', styles: [ { title: 'Normal', value: 'normal' }, { title: 'Heading 1', value: 'h1' }, { title: 'Heading 2', value: 'h2' } ], marks: { decorators: [ { title: 'Strong', value: 'strong' }, { title: 'Emphasis', value: 'em' } ] } } ]
那你的lib/richtextEditor.js必须完全导出这个数组,不能改变结构:
// lib/richtextEditor.js export default [ { type: 'block', styles: [ { title: 'Normal', value: 'normal' }, { title: 'Heading 1', value: 'h1' }, { title: 'Heading 2', value: 'h2' } ], marks: { decorators: [ { title: 'Strong', value: 'strong' }, { title: 'Emphasis', value: 'em' } ] } } ];
2. 在Schema中正确导入并使用
根据导出方式匹配导入语法:
- 如果用默认导出(如上例),导入语句为
import editor from '../../lib/richtextEditor.js'; - 如果用命名导出(比如
export const editorConfig = [...]),则导入语句为import { editorConfig } from '../../lib/richtextEditor.js';
然后在字段中直接使用导入的变量,和之前写死的内容用法完全一致:
// 你的Schema文件 import editor from '../../lib/richtextEditor.js'; export default { name: 'yourDocumentType', title: 'Your Document', type: 'document', fields: [ { title: 'Abstract', name: 'abstract', type: 'array', of: editor } ] }
3. 排查常见错误
- 导出/导入不匹配:如果导出的是单个对象(
export default {...}),但of字段需要数组,会直接报错,必须保证导出结构和原代码一致。 - 语法遗漏:检查
richtextEditor.js是否有语法错误,比如抽离时不小心删掉的逗号、括号,这类问题会导致文件加载失败。 - 路径验证:可以尝试用项目根目录相对路径(比如
./lib/richtextEditor.js)再次确认路径正确性。
内容的提问来源于stack exchange,提问作者Rockwell Rice
相关产品推荐
相关产品推荐

