Editor
主编辑器实例。用于生命周期事件、各类管理器以及命令执行。
主编辑器实例。用于生命周期事件、各类管理器以及命令执行。
表示画布树中的一个节点。适用于类型化的事件处理器和自定义特性(trait)。
可拖拽的构建模块。类型安全的区块定义能减少运行时内容错误。
通过 ComponentManager.addType() 注册新组件类型时使用。
为默认值和特性提供强类型约束,让团队成员复用同一套组件契约。
涵盖本地或远程持久化流程中的存储配置与操作。
步骤 01
在编写编辑器逻辑前启用 strict 模式和 noImplicitAny,尽早发现插件和组件的错误。
步骤 02
在初始化流程中使用 Editor | null,并在异步回调中调用管理器 API 前加上判空保护。
步骤 03
定义带默认值的选项接口,使插件 API 在不同项目和版本间保持稳定。
步骤 04
通过共享的 TypeScript 类型统一组件特性和默认值,让团队保持一致。
从第一天起就为编辑器初始化和事件流添加类型。这能尽早发现无效的管理器调用和事件载荷错误。
import grapesjs from 'grapesjs';
import type { Editor, Component, Block } from 'grapesjs';
// Typed editor instance
let editor: Editor | null = null;
editor = grapesjs.init({
container: '#gjs',
storageManager: false,
});
// Typed event handlers
editor.on('component:add', (component: Component) => {
console.log('Added component:', component.get('type'));
});
// Typed block access
const blockManager = editor.BlockManager;
const blocks: Block[] = blockManager.getAll().models;定义插件选项接口和默认值,让你的扩展对团队更安全,并在各个版本间保持可预期的行为。
import type { Editor } from 'grapesjs';
interface MyPluginOptions {
apiKey?: string;
debug?: boolean;
}
const myPlugin = (editor: Editor, opts: MyPluginOptions = {}) => {
const { apiKey = '', debug = false } = opts;
editor.BlockManager.add('custom-block', {
label: 'Custom Block',
category: 'Custom',
content: '<div class="custom-block">Custom content</div>',
});
if (debug) {
console.log('Plugin initialized with API key:', apiKey);
}
};
export default myPlugin;类型化的组件定义能减少运行时特性错误,并帮助产品团队创建可复用的内容模型。
import type { ComponentDefinition, ComponentProperties } from 'grapesjs';
// Typed component definition
const heroComponent: ComponentDefinition = {
model: {
defaults: {
tagName: 'section',
draggable: true,
droppable: false,
attributes: { class: 'hero-section' },
traits: [
{ type: 'text', name: 'headline', label: 'Headline' },
{ type: 'text', name: 'subheadline', label: 'Subheadline' },
],
} as ComponentProperties,
},
};
editor.ComponentManager.addType('hero', heroComponent);所有高级插件均包含 TypeScript 类型定义,让集成更安全、更高效。
浏览插件