quanshiyinian 发表于 2020-1-9 16:57:22

Gutenberg Sidebar边栏开发心得的案例

文章目录[隐藏]
[*]安装Node
[*]准备开发环境
[*]PHP引入脚本
[*]开始编写Gutenberg边栏

[*]注册Meta元数据
[*]其他优化
[*]总结
[*]关于本文的其它说明
[*]参考文献

这是一篇手把手教你开发WordPress Gutenberg Sidebar的文章。虽然之前也写了很多关于Gutenberg的开发心得,不过都直接忽略了环境的安装和配置,以至于很多新手对于ES Next的编译仍然无法下手。因此本文在写Gutenberg Sidebar开发心得的时候,加上了环境配置的部分。安装Node从Node官方网站下载符合你系统版本的Node进行安装,过程就是下一步下一步完成一类的。App安装过程省略。准备开发环境1、在主题内新建一个文件夹,这个文件夹可以放置到任何位置,例如我在pandastudio_plugins目录下新建了一个sample_gutenberg_sidebar2、打开这个文件夹,按住Shift右键单击空百处,选择打开Powershell(Win10以前的系统应该是命令行)。Mac系统手动打开系统自带Shell,输入cd空格,将文件夹拖入到Shell窗口回车即可3、输入npm init来创建一个项目,回车后,会让你输入包名称、项目名称、版本号等,全部按回车即可。大致效果如下:PS D:\apps\xampp\htdocs\wordpress\wp-content\themes\reVival\pandastudio_plugins\sample_gutenberg_sidebar> npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.


See `npm help json` for definitive documentation on these fields
and exactly what they do.


Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.


Press ^C at any time to quit.
package name: (sample_gutenberg_sidebar)
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to D:\apps\xampp\htdocs\wordpress\wp-content\themes\reVival\pandastudio_plugins\sample_gutenberg_sidebar\package.json:


{
"name": "sample_gutenberg_sidebar",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}




Is this OK? (yes)
PS D:\apps\xampp\htdocs\wordpress\wp-content\themes\reVival\pandastudio_plugins\sample_gutenberg_sidebar>4、可以看到,目录下已经出现了一个package.json文件。现在先不管它,我们继续在这个目录安装开发需要的 @wordpress/scripts 依赖,继续在刚才的命令行中输入npm install @wordpress/scripts -D5、根据网络情况,可能需要下载一段时间,然后自动安装。此过程中可以看到一个进度条以及下载的包名称,效果如下[................] \ fetchMetadata: sill XXXXXXX如果安装一次等了很久屏幕都没有动静,可以连续按下几次Ctrl+C来终止,然后继续输入前面的命令来重新安装6、安装完依赖之后,在刚才的文件夹下新建src文件夹,然后在里面新建index.js文件作为未编译的原始文件7、打开package.json,将scripts里面的内容修改为下面的内容, 保存后关闭"scripts": {
    "dev": "wp-scripts start",
    "build": "wp-scripts build"
},8、在刚才的PowerShell命令行中输入下面的命令来开始开发:npm run dev9、命令运行后,将监听src/index.js文件的变化来自动编译,大致效果如下:PS D:\apps\xampp\htdocs\wordpress\wp-content\themes\reVival\pandastudio_plugins\sample_gutenberg_sidebar> npm run dev


> sample_gutenberg_sidebar@1.0.0 dev D:\apps\xampp\htdocs\wordpress\wp-content\themes\reVival\pandastudio_plugins\sample_gutenberg_sidebar
> wp-scripts start




webpack is watching the files…


Live Reload listening on port 35729


Hash: f06cbcda0a4aad106cd6
Version: webpack 4.8.3
Time: 1495ms
Built at: 2019-08-16 09:41:56
          Asset      SizeChunks             Chunk Names
       index.js2.79 KiB   indexindex
   index.js.map2.52 KiB   indexindex
index.deps.json15 bytes   indexindex
Entrypoint index = index.js index.js.map index.deps.json
[./src/index.js] 0 bytes {index} 10、此时可以看到在原来的文件夹下生成了一个build的文件夹,里面的index.js就是编译后的脚本了。这样,一个Gutenberg的脚本开发环境就搭建好了。PHP引入脚本1、PHP引入脚本的方法都是一样的:使用钩子来进行引入。在主题的function.php文件中添加一个enqueue_block_editor_assets的动作,然后在执行此动作的时候注册和引入脚本即可<?php
add_action( 'enqueue_block_editor_assets', function(){
    wp_register_script(
      'sample_gutenberg_sidebar',
      get_stylesheet_directory_uri()."https://static.wpdaxue.com/pandastudio_plugins/sample_gutenberg_sidebar/build/index.js",
      array( 'wp-plugins', 'wp-edit-post', 'wp-element' )
    );
    wp_enqueue_script( 'sample_gutenberg_sidebar' );
});2、要验证是否成功引入了,可以在src/index.js里面输入下面的内容来测试(保证在开发状态,已经运行了npm run dev)alert('已成功引入!');3、接下来在开发环境中用浏览器打开Gutenberg编辑器,刷新后即可看到“已成功引入”的弹窗。下面就可以开始正式编写Gutenberg的边栏脚本了。开始编写Gutenberg边栏注册Meta元数据1、我们的边栏数据都是存储在Post的Meta里面的,因此需要先注册Meta然后才可以使用,假设现在需要注册一个叫做sample_meta1的字符串数据,我们在function.php里面这样写register_post_meta( 'post', 'sample_meta1', array(
    'show_in_rest' => true,
    'single' => true,
    'type' => 'string'
));2、在src/index.js里面编写边栏的前端部分//引入需要的模块const {    registerPlugin} = wp.plugins;const {    PluginSidebar,    PluginSidebarMoreMenuItem} = wp.editPost;const {    withSelect,    withDispatch} = wp.data;const {    Fragment} = wp.element;const {    TextControl,} = wp.components; //注册边栏registerPlugin( 'sample-gutenberg-sidebar', {    render() {      return (            <Fragment>                <PluginSidebar                name="sample-gutenberg-sidebar"                icon="admin-post"                title="边栏示例"                >                示例内容                </PluginSidebar>            </Fragment>      )    },} );

打开编辑器,看到效果如下


3、刚才注册的边栏直接取消固定并关闭(取消星星的填充,然后点击右侧的叉叉)后,就再也无法打开了,因此需要在Gutenberg的选项中增加一个边栏的打开菜单,我们在<Fragment>里面增加一个<PluginSidebarMoreMenuItem>并通过target属性指向到边栏
<PluginSidebarMoreMenuItem target="sample-gutenberg-sidebar">
边栏菜单
</PluginSidebarMoreMenuItem>这样,哪怕边栏被取消固定并关闭后,也可以有再次打开的方法:

4、现在,边栏的内容都是完全空的,我们来增加一个Input输入框来编辑刚才注册的sample_meta1数据。这一部分的原理在Gutenberg开发手册上有详细的描述我就不再多说了,主要使用了withSelect和withDispatch来实现数据的读取和更新。考虑到如果注册的meta字段比较多,这一部分就会重复写很多次而且比较繁琐,因此我将它封装成了一个构建meta模块的函数,后面的新增meta模块都用这个方法来进行:
const createMetaBlock = (metaBlockField,metaName) => {
    const MetaBlockFieldWithDataAndActions = withDispatch((dispatch) => {
            return {
                setMetaFieldValue(value) {
                  let meta = {};
                  meta = value;
                  dispatch('core/editor').editPost({meta});
                }
            }
      })(withSelect((select) => {
            return {
                metaFieldValue: select('core/editor').getEditedPostAttribute('meta')
            }
      })(metaBlockField));
    return (<MetaBlockFieldWithDataAndActions />);
}

我上面封装的构建模块方法第一个参数是Function类型:它接收一个参数(参数中包含meta数据和设置meta数据的方法),返回需要传入的组件;第二个参数是String类型,内容是meta字段的名称。将上面的代码加入到我们的脚本中后,现在我们用我刚才封装的方法来添加sample_meta1的编辑框
<PluginSidebar
name="sample-gutenberg-sidebar"
icon="admin-post"
title="边栏示例"
>
{
    createMetaBlock(({metaFieldValue,setMetaFieldValue})=>{return (
      <TextControl
      label="示例数据1"
      value={metaFieldValue}
      onChange={ (content) => {setMetaFieldValue(content)} }
      />
    )},'sample_meta1')
}
</PluginSidebar>如果有更多的数据字段如sample_meta2,只需要在PluginSidebar中添加更多的metaBolck方法即可。编辑器中效果如下

5、至此,Gutenberg边栏的编写就完成了。发布时,先删除build文件夹,然后在PowerShell中使用下面的命令来进行代码打包和代码压缩
npm run build

开发文件夹下的package.json、src、node_modules、package-lock.json都不需要发布到正式环境中,只有build文件夹才需要
其他优化
[*]我们可以看到,上面的样式不算太好看。因此可以用类似引入脚本的方法,一样用钩子去引入样式。这里我就不再做示例了。发挥自己的想象去完成它吧
[*]根据实际的需求,可能不止input输入框一种,因此还可以根据需要增加更多的组件进去
[*]如果不想使用边栏,也可以将PluginSidebar换成PluginDocumentSettingPanel(具体用法参考Gutenberg开发文档),就可以将设置选项直接集成到文章设置页里面了
[*]最终,我完成了一个包含“图片上传”、“色彩选择”、“多图上传”、“单选”、“下拉”等功能为一体的主题文章设置工具,如下所示:
[*]
[*]总结Gutenberg Sidebar 边栏开发时都是使用基础的PluginSidebar组件进行开发,只需掌握使用方法即可。唯一需要注意不要被坑的是要记得添加边栏菜单的另一个入口,防止被关闭后无法再次打开。Meta数据的读取和写入本身是一个难点,不过在本文中我已经将它封装成一个方便重用的方法了,若需了解详情,建议参考本文末尾的官方教程学习原理即可。关于本文的其它说明本文特色图在设计时考虑了Node的Logo外形和Gutenberg的G进行融合,文章头图也致敬了Node的颜色和风格。头图使用了“多边形”生成工具辅助进行设计。



页: [1]
查看完整版本: Gutenberg Sidebar边栏开发心得的案例