使用 webpack build 在插件中注册多个自定义 gutenberg 块

Registering multiple custom gutenberg blocks in a plugin with webpack build

我正在开发一个捆绑多个自定义 gutenberg 块的插件,我正在使用 @wordpress/scripts npm 模块与 webpack 一起构建。到目前为止效果很好,但是在编辑器中工作时检查控制台会给我关于块已经注册的错误。目前我有 5 个块,每个块有 4 个错误,所以我假设在我的插件 PHP 中的每个注册函数调用中,所有块都尝试再次注册。每个块都有自己的 src-js 文件,并且都被捆绑到一个 build-js 中。此外,每个块都有自己的寄存器函数,PHP 中有 add_action,但 plugins_url 始终是相同的 build-js。我认为我的 PHP 文件处理注册的方式存在问题,但老实说,我一直在思考如何解决这个问题。我仍然在为使用块开发带来的所有变化而苦苦挣扎。也许有人已经这样做了并且可以指出正确的方向?

示例 PHP 包含 2 个块的代码

<?php
/*
Plugin Name: My Blocks Plugin
*/

/* Block 1 */

function register_my_block_1() {
    wp_register_script(
        'foo-my-block-1',
        plugins_url( 'build/index.js', __FILE__ ),
        array( 'wp-blocks', 'wp-element', 'wp-editor' )
    );

    register_block_type( 'foo/my-block-1', array(
        'editor_script' => 'foo-my-block-1',
    ) );

}
add_action( 'init', 'register_my_block_1' );

/* Block 2 */

function register_my_block_2() {
    wp_register_script(
        'foo-my-block-2',
        plugins_url( 'build/index.js', __FILE__ ),
        array( 'wp-blocks', 'wp-i18n' )
    );

    register_block_type( 'foo/my-block-2', array(
        'editor_script' => 'foo-my-block-2',
    ) );

}
add_action( 'init', 'register_my_block_2' );

wp_register_script() 和所有依赖项定义 build-JS 就足够了,然后用 register_block_type():

注册每个块
function plugin_slug_register_blocks() {

    // Register build.js
    wp_register_script(
      'plugin-slug-blocks',
        plugins_url( 'build.js', __FILE__ ),
        array( 'wp-blocks', 'wp-element', 'wp-data' )
    );

    // Register Block 1
    register_block_type( 'plugin-slug/block-name-1', array(
       'editor_script' => 'plugin-slug-blocks',
    ) );

    // Register Block 2
    register_block_type( 'plugin-slug/block-name-2', array(
        'editor_script' => 'plugin-slug-blocks',
    ) );
}
add_action( 'init', 'plugin_slug_register_blocks' );

除了 editor_script,register_block_type() 也接受样式和 editor_style 作为 CSS 文件的参数。如果是动态块,还可以通过render_callback.

传递一个render函数