Gutenberg.js 开源项目教程
1、项目介绍
Gutenberg.js 是一个基于 WordPress Gutenberg 编辑器的 JavaScript 版本,旨在使 Gutenberg 编辑器能够更灵活地集成到非 WordPress 的应用中。该项目允许开发者通过 npm 安装,并提供了丰富的 API 和自定义选项,以便在各种前端应用中使用 Gutenberg 编辑器。
2、项目快速启动
安装
首先,通过 npm 安装 Gutenberg.js:
npm install @frontkom/gutenberg-js
引入和初始化
在你的项目中引入必要的脚本并初始化 Gutenberg 编辑器:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Gutenberg.js 示例</title>
<script src="https://unpkg.com/@frontkom/gutenberg-js"></script>
</head>
<body>
<div id="editor"></div>
<script>
const { default: initializeEditor } = window.wp.editPost;
initializeEditor('editor', 'post', 1, {
canAutosave: false,
canPublish: false,
canSave: false,
mediaLibrary: false
});
</script>
</body>
</html>
3、应用案例和最佳实践
自定义块
Gutenberg.js 允许开发者注册自定义块,以下是一个简单的自定义块示例:
const { registerBlockType } = window.wp.blocks;
const { RichText } = window.wp.editor;
registerBlockType('my-namespace/custom-block', {
title: 'Custom Block',
icon: 'smiley',
category: 'common',
attributes: {
content: {
type: 'array',
source: 'children',
selector: 'p',
},
},
edit(props) {
const { attributes: { content }, setAttributes } = props;
return (
<RichText
tagName="p"
onChange={(newContent) => setAttributes({ content: newContent })}
value={content}
/>
);
},
save(props) {
const { attributes: { content } } = props;
return <RichText.Content tagName="p" value={content} />;
},
});
事件处理
Gutenberg.js 提供了丰富的事件系统,以下是一个简单的事件监听示例:
const { subscribe } = window.wp.data;
subscribe(() => {
console.log('Editor state changed!');
});
4、典型生态项目
集成 TinyMCE
Gutenberg.js 依赖于 TinyMCE 文本编辑器,确保在项目中引入 TinyMCE:
<script src="https://cdn.tiny.cloud/1/no-api-key/tinymce/5/tinymce.min.js" referrerpolicy="origin"></script>
集成 React
Gutenberg.js 基于 React 构建,确保在项目中引入 React 和 React-DOM:
<script src="https://unpkg.com/react@16.6.3/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16.6.3/umd/react-dom.production.min.js"></script>
通过以上步骤,你可以在非 WordPress 环境中快速启动并使用 Gutenberg.js,实现丰富的内容编辑功能。