Плагин React на Wordpress не работает index. js - PullRequest
0 голосов
/ 14 июля 2020

Я пытаюсь добавить плагин шорткода React в Wordpress. Я следую этому руководству, хотя и в среде Windows (https://www.digitalocean.com/community/tutorials/how-to-embed-a-react-application-in-wordpress-on-ubuntu-18-04).

Что происходит, так это то, что я могу найти только пустой целевой элемент () в DOM, и ничего не отображается внутри него.

Я использую WordPress версии 5.4.2 и последнее приложение create-response-app, поскольку более старое приложение не генерирует файлы шаблонов.

Структура каталогов соответствует ниже: response-wordpress

  • react-wordpress. php
  • включает
    • enqueue. php
    • шорткод. php
  • widget {app created by create-react-app}
// enqueue.php
<?php
defined( 'ABSPATH' ) or die( 'Direct script access disallowed.' );

add_action( 'init', function() {

    add_filter( 'script_loader_tag', function( $tag, $handle ) {
        if ( ! preg_match( '/^erw-/', $handle ) ) { return $tag; }
        return str_replace( ' src', ' async defer src', $tag );
    }, 10, 2 );

    add_action( 'wp_enqueue_scripts', function() {
        $asset_manifest = json_decode( file_get_contents( ERW_ASSET_MANIFEST ), true )['files'];

        if ( isset( $asset_manifest[ 'main.css' ] ) ) {
            wp_enqueue_style( 'erw', get_site_url() . $asset_manifest[ 'main.css' ] );
        }

        wp_enqueue_script( 'erw-runtime', get_site_url() . $asset_manifest[ 'runtime~main.js' ], array(), null, true );

        wp_enqueue_script( 'erw-main', get_site_url() . $asset_manifest[ 'main.js' ], array('erw-runtime'), null, true );

        foreach ( $asset_manifest as $key => $value ) {
            if ( preg_match( '@static/js/(.*)\.chunk\.js@', $key, $matches ) ) {
                if ( $matches && is_array( $matches ) && count( $matches ) === 2 ) {
                    $name = "erw-" . preg_replace( '/[^A-Za-z0-9_]/', '-', $matches[1] );
                    wp_enqueue_script( $name, get_site_url() . $value, array( 'erw-main' ), null, true );
                }
            }

            if ( preg_match( '@static/css/(.*)\.chunk\.css@', $key, $matches ) ) {
                if ( $matches && is_array( $matches ) && count( $matches ) == 2 ) {
                    $name = "erw-" . preg_replace( '/[^A-Za-z0-9_]/', '-', $matches[1] );
                    wp_enqueue_style( $name, get_site_url() . $value, array( 'erw' ), null );
                }
            }
        }
    });
});
// shortcode.php
<?php
// This file enqueues a shortcode.

defined( 'ABSPATH' ) or die( 'Direct script access disallowed.' );

add_shortcode( 'erw_widget', function( $atts ) {
    $default_atts = array();
    $args = shortcode_atts( $default_atts, $atts );

    return "<div id='erw-root'></div>";
});
// react-wordpress.php
<?php
/**
 * @wordpress-plugin
 * Plugin Name:       Embedding React In Wordpress
 */

defined( 'ABSPATH' ) or die( 'Direct script access diallowed.' );

define( 'ERW_WIDGET_PATH', plugin_dir_path( __FILE__ ) . '/widget' );
define( 'ERW_ASSET_MANIFEST', ERW_WIDGET_PATH . '/build/asset-manifest.json' );
define( 'ERW_INCLUDES', plugin_dir_path( __FILE__ ) . '/includes' );

require_once( ERW_INCLUDES . '/enqueue.php' );
require_once( ERW_INCLUDES . '/shortcode.php' );
// react-wordpress/widet/src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

console.log('hello1'); // Does not show up in console

window.onload = () => {

    console.log('hello2'); // Does not show up in console

    const target = document.getElementById('erw-root');
    if (target) { ReactDOM.render(<App />, target); }

    serviceWorker.unregister();
};

Спасибо всем за любую помощь

...