WordPress 编辑器的区块库。
安装
安装模块
npm install @wordpress/block-library --save
此包假设您的代码将在ES2015+环境中运行。如果您使用的环境对这类语言特性和 API 支持有限或完全不支持,您应该在代码中包含@wordpress/babel-preset-default随附的 polyfill。
API
registerCoreBlocks
用于注册区块编辑器提供的核心区块的函数。
用法
import { registerCoreBlocks } from '@wordpress/block-library';
registerCoreBlocks();
参数
- blocks
Array:可选的核心区块注册数组。
注册单个区块
- 当您在文件导入时才关心注册区块:
import '@wordpress/block-library/build-module/verse/init'; - 当您需要在使用后自动注册的区块引用时:
import verseBlock from '@wordpress/block-library/build-module/verse/init'; - 当您需要完全控制区块的注册时机时:
import { init } from '@wordpress/block-library/build-module/verse'; const verseBlock = init();
为此包做出贡献
这是 Gutenberg 项目的一个独立包。该项目以 monorepo(单体仓库)形式组织。它由多个自包含的软件包组成,每个包都有特定的用途。此 monorepo 中的包发布到 npm,并被 WordPress 以及其他软件项目使用。
要了解有关为此包或整个 Gutenberg 做出贡献的更多信息,请阅读项目的主要 贡献者指南。
添加新区块
⚠️ 向此包添加新区块需要额外的步骤!
- 不要忘记在此包的
index.jsx文件中注册新的核心区块。例如,如果您要添加名为core/blinking-paragraph的新核心区块,则需要添加类似以下内容:// packages/block-library/src/index.jsx import * as blinkingParagraph from './blinking-paragraph';然后将
blinkingParagraph添加到getAllBlocks()函数中的列表中。如果是实验性功能,请在
block.json中添加以下属性:{ "__experimental": "true" } - 在
lib/blocks.php文件的gutenberg_reregister_core_block_types()函数中注册区块。如果它是 静态区块,则将其添加到block_folders数组;如果它是 动态区块,则将其添加到block_names数组。 将
init.js文件添加到新区块的目录中:import { init } from './'; export default init();当使用从
@wordpress/block-library包注册单个区块的选项时,会使用此文件。如果区块在前端公开了一个脚本模块,则必须将其包含在包的
package.json文件的wpScriptModules对象中。这将使脚本模块在捆绑用于 WordPress 时被包含。请参阅 包的 README 了解更多详情。:{ "name": "@wordpress/block-library", "wpScriptModuleExports": { "./blinking-paragraph/view": "./build-module/blinking-paragraph/view.js", "./image/view": "./build-module/image/view.js" // 在此处添加任何新的脚本模块。 } }对于每个动态区块,您需要在区块的
render_callback中手动排入视图脚本模块,示例如下:function render_block_core_blinking_paragraph( $attributes, $content ) { $should_load_view_script = ! empty( $attributes['isInteractive'] ); if ( $should_load_view_script ) { wp_enqueue_script_module( '@wordpress/block-library/blinking-paragraph' ); } return $content; }
PHP 函数的命名约定
在 packages/block-library/src/ 目录的子目录中声明的所有 PHP 函数名应以以下前缀之一开头:
block_core_<directory_name>render_block_core_<directory_name>register_block_core_<directory_name>
在此上下文中,<directory_name> 表示相应 .php 文件所在的目录名称。
目录名称转换为小写,除字母和数字外的所有字符都替换为下划线。
示例:
对于在 packages/block-library/src/my-block/index.php 文件中声明的 PHP 函数,正确的前缀应为:
block_core_my_blockrender_block_core_my_blockregister_block_core_my_block
使用特定插件的前缀/后缀
与 /lib 目录中的 PHP 代码不同,您通常应避免在区块 PHP 文件中的函数和其他代码上应用特定插件的前缀/后缀,例如 gutenberg_。
然而,有时区块可能需要使用 Gutenberg 函数,即使存在 Core 等效项,例如,当 Gutenberg 函数依赖于仅在插件中可用的代码时。
在这种情况下,您可以在区块 PHP 代码中使用相应的 Core wp_ 函数,并将其名称添加到 package.json 中的前缀函数列表中。
在构建时,Webpack 将搜索该列表中的 wp_ 函数,并将其替换为它们的 gutenberg_ 等效项。此过程确保插件调用 gutenberg_ 函数,但当更新向后移植时,区块仍将调用 Core wp_ 函数。
Webpack 假设除了前缀外,函数名是相同的:wp_get_something_useful() 将被替换为 gutenberg_get_something_useful()。