代码之家  ›  专栏  ›  技术社区  ›  Alexander A

为wordpress插件扩展webpack配置创建块交互模板不起作用

  •  0
  • Alexander A  · 技术社区  · 2 年前

    我使用wordpress交互式模板@wordpress/create-block交互式模板创建了一个插件。我想创建一个自定义的Gutenberg块,但也有一个管理页面来管理它。对于管理页面,我想使用wordpress组件。但是,我不知道如何确保它包含在构建文件夹中。据我所知,为了构建一个自定义文件,我需要修改webpack配置,因为我只想将其包含在管理面板页面中。

    当我试图扩展webpack配置时,我在运行时遇到了这个错误 npm run build :

    webpack-cli] Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
     - configuration has an unknown property '1'. These properties are valid:
       object { amd?, bail?, cache?, context?, dependencies?, devServer?, devtool?, entry?, experiments?, extends?, externals?, externalsPresets?, externalsType?, ignoreWarnings?, infrastructureLogging?, loader?, mode?, module?, name?, node?, optimization?, output?, parallelism?, performance?, plugins?, profile?, recordsInputPath?, recordsOutputPath?, recordsPath?, resolve?, resolveLoader?, snapshot?, stats?, target?, watch?, watchOptions? }
       -> Options object as provided by the user.
       For typos: please correct them.
       For loader options: webpack >= v2.0.0 no longer allows custom properties in configuration.
         Loaders should be updated to allow passing options via loader options in module.rules.
         Until loaders are updated one can use the LoaderOptionsPlugin to pass these options to the loader:
         plugins: [
           new webpack.LoaderOptionsPlugin({
             // test: /\.xxx$/, // may apply this only for some modules
             options: {
               1: …
             }
           })
         ]
    

    这是相关的代码;

    webpack.config.js:

    // Import the original config from the @wordpress/scripts package.
    const defaultConfig = require( '@wordpress/scripts/config/webpack.config' );
    
    
    // Import the helper to find and generate the entry points in the src directory
    const { getWebpackEntryPoints } = require( '@wordpress/scripts/utils/config' );
    
    
    // Add a new entry point by extending the Webpack config.
    module.exports = {
       ...defaultConfig,
       entry: {
           ...getWebpackEntryPoints(),
           custom: './src/admin.js',
       },
    };
    

    restaurant-booking.php:

    <?php
    /**
     * Plugin Name:       Restaurant Booking
     * Description:       An interactive block with the Interactivity API
     * Version:           0.1.0
     * Requires at least: 6.1
     * Requires PHP:      7.0
     * Author:            The WordPress Contributors
     * License:           GPL-2.0-or-later
     * License URI:       https://www.gnu.org/licenses/gpl-2.0.html
     * Text Domain:       restaurant-booking
     *
     * @package           create-block
     */
    
    if ( ! defined( 'ABSPATH' ) ) {
        exit; // Exit if accessed directly.
    }
    
    /**
     * Registers the block using the metadata loaded from the `block.json` file.
     * Behind the scenes, it registers also all assets so they can be enqueued
     * through the block editor in the corresponding context.
     *
     * @see https://developer.wordpress.org/reference/functions/register_block_type/
     */
    function create_block_restaurant_booking_block_init() {
        register_block_type_from_metadata( __DIR__ . '/build' );
    }
    add_action( 'init', 'create_block_restaurant_booking_block_init' );
    
    
    /**
     * Create a new admin page.
     */
    function my_admin_menu() {
        // Create a new admin page for our app.
        add_menu_page(
            __( 'My custom Gutenberg app', 'block-development-examples' ),
            __( 'My custom Gutenberg app', 'block-development-examples' ),
            'manage_options',
            'my-custom-gutenberg-app',
            function () {
                echo '
                <h2>Pages</h2>
                <div id="my-custom-gutenberg-app"></div>
            ';
            },
            'dashicons-schedule',
            3
        );
    }
    
    add_action( 'admin_menu', 'my_admin_menu' );
    
    
    /**
     * Load the admin script.
     *
     * @param string $hook The hook name of the page.
     */
    function load_custom_wp_admin_scripts( $hook ) {
        // Load only on ?page=my-custom-gutenberg-app.
        if ( 'toplevel_page_my-custom-gutenberg-app' !== $hook ) {
            return;
        }
        $asset_file = include plugin_dir_path( __FILE__ ) . '/build/index.asset.php';
    
        foreach ( $asset_file['dependencies'] as $style ) {
            wp_enqueue_style( $style );
        }
    
        wp_register_script(
            'my-custom-gutenberg-app',
            plugins_url( 'build/admin.js', __FILE__ ),
            $asset_file['dependencies'],
            $asset_file['version'],
            true
        );
        wp_enqueue_script( 'my-custom-gutenberg-app' );
    }
    
    add_action( 'admin_enqueue_scripts', 'load_custom_wp_admin_scripts' );
    

    src/admin.js

    import { SearchControl } from '@wordpress/components';
    import { useState, createRoot } from '@wordpress/element';
    import { useSelect } from '@wordpress/data';
    import { store as coreDataStore } from '@wordpress/core-data';
    
    //import { Notifications, CreatePageButton, PagesList } from './components/';
    import './admin.scss';
    
    function MyFirstApp() {
        const [ searchTerm, setSearchTerm ] = useState( '' );
        const { pages, hasResolved } = useSelect(
            ( select ) => {
                const query = {};
                if ( searchTerm ) {
                    query.search = searchTerm;
                }
                const selectorArgs = [ 'postType', 'page', query ];
                return {
                    pages: select( coreDataStore ).getEntityRecords(
                        ...selectorArgs
                    ),
                    hasResolved: select( coreDataStore ).hasFinishedResolution(
                        'getEntityRecords',
                        selectorArgs
                    ),
                };
            },
            [ searchTerm ]
        );
    
        return (
            <div>
                <div className="list-controls">
                    <p>HELLO WORLD</p>
                </div>
            </div>
        );
    }
    
    window.addEventListener(
        'load',
        function () {
            const rootDomElement = document.getElementById(
                'my-custom-gutenberg-app'
            );
            const root = createRoot( rootDomElement );
            root.render( <MyFirstApp /> );
        },
        false
    );
    

    src/index.js

    /**
     * Registers a new block provided a unique name and an object defining its behavior.
     *
     * @see https://developer.wordpress.org/block-editor/developers/block-api/#registering-a-block
     */
    import { registerBlockType } from '@wordpress/blocks';
    
    /**
     * Lets webpack process CSS, SASS or SCSS files referenced in JavaScript files.
     * All files containing `style` keyword are bundled together. The code used
     * gets applied both to the front of your site and to the editor. All other files
     * get applied to the editor only.
     *
     * @see https://www.npmjs.com/package/@wordpress/scripts#using-css
     */
    import './style.scss';
    import './editor.scss';
    
    /**
     * Internal dependencies
     */
    import Edit from './edit';
    import metadata from './block.json';
    
    /**
     * Every block starts by registering a new block type definition.
     *
     * @see https://developer.wordpress.org/block-editor/developers/block-api/#registering-a-block
     */
    registerBlockType( metadata.name, {
        /**
         * @see ./edit.js
         */
        edit: Edit,
    } );
    

    package.json:

    {
        "name": "restaurant-booking",
        "version": "0.1.0",
        "description": "An interactive block with the Interactivity API",
        "author": "The WordPress Contributors",
        "license": "GPL-2.0-or-later",
        "main": "build/index.js",
        "scripts": {
            "build": "wp-scripts build --experimental-modules",
            "format": "wp-scripts format",
            "lint:css": "wp-scripts lint-style",
            "lint:js": "wp-scripts lint-js",
            "packages-update": "wp-scripts packages-update",
            "plugin-zip": "wp-scripts plugin-zip",
            "start": "wp-scripts start --experimental-modules"
        },
        "files": [
            "*"
        ],
        "dependencies": {
            "@wordpress/interactivity": "^5.7.0"
        },
        "devDependencies": {
            "@wordpress/scripts": "^27.9.0"
        }
    }
    
    0 回复  |  直到 2 年前