You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Drupal 8中通过自定义模块集成React应用?求流程与方法

Hey there! I’ve been through this exact integration before, so let me walk you through the full step-by-step process to get your React SPA working with a Drupal 8 controller. Let’s break this down clearly:

Step 1: Prepare Your React Application
  • First, build your React SPA for production using npm run build (or yarn build if you use Yarn). This generates a build folder with all static assets (HTML, CSS, JS, images).
  • You can host these assets directly in your custom Drupal module or Drupal’s sites/default/files directory. For simplicity, let’s place them in a subfolder of your custom module: modules/custom/react_integration/react_app/build.
Step 2: Set Up Your Drupal Custom Module

Assuming you already have a custom module (we’ll call it react_integration), add these key components:

2.1 Define a Library for React Assets

Create a react_integration.libraries.yml file in your module root to register React’s static files with Drupal:

react_app:
  version: 1.x
  js:
    react_app/build/static/js/main.[hash].js: { minified: true }
    react_app/build/static/js/2.[hash].js: { minified: true } # Update with actual hash from your build output
  css:
    theme:
      react_app/build/static/css/main.[hash].css: { minified: true }
  dependencies:
    - core/jquery
    - core/drupal # Optional, only if you need Drupal's JS APIs

Note: Replace [hash] with the actual hash strings from your React build folder—Drupal needs exact filenames to load assets correctly.

2.2 Create a Controller to Render the React App

Make a src/Controller/ReactAppController.php file in your module to handle the route and mount React:

<?php

namespace Drupal\react_integration\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Render\Markup;

/**
 * Controller for rendering the React SPA.
 */
class ReactAppController extends ControllerBase {

  /**
   * Render the React application.
   *
   * @return array
   *   A Drupal render array.
   */
  public function content() {
    // Attach the React library we defined
    $build['#attached']['library'][] = 'react_integration/react_app';

    // Add the root div where React will mount its app
    $build['react_root'] = [
      '#markup' => Markup::create('<div id="root"></div>'),
    ];

    // Disable page cache for this route (useful during development)
    $build['#cache']['max-age'] = 0;

    return $build;
  }

}

2.3 Add a Route to Access the Controller

Create a react_integration.routing.yml file to map a URL to your controller:

react_integration.app:
  path: '/react-app' # This is the URL where your React app will live
  defaults:
    _controller: '\Drupal\react_integration\Controller\ReactAppController::content'
    _title: 'My React SPA'
  requirements:
    _permission: 'access content' # Adjust permissions based on your needs
Step 3: Enable the Module and Test
  • Go to Drupal’s Extend page (/admin/modules), find your react_integration module, and enable it.
  • Clear Drupal’s cache (use /admin/config/development/performance or run drush cr via the command line).
  • Visit the URL you defined (/react-app)—your React SPA should load and mount into the #root div!
Bonus Tips for Development & Advanced Use Cases
  • Development Mode: For hot reloading during React development, skip building for production. Instead, set "proxy": "http://your-drupal-site.local" in your React app’s package.json, then in your controller, add a script tag pointing to http://localhost:3000/static/js/bundle.js (your React dev server’s JS path) instead of production assets.
  • Pass Drupal Data to React: To send data like user info or content from Drupal to React, add it as a Drupal setting:
    // In your controller's content() method
    $build['#attached']['drupalSettings']['react_integration']['user'] = [
      'name' => $this->currentUser()->getDisplayName(),
      'id' => $this->currentUser()->id(),
    ];
    
    Access it in React via window.drupalSettings.react_integration.user.
  • Fetch Data from Drupal: Use Drupal’s built-in JSON:API module or REST module to create endpoints your React app can call with fetch or Axios.

内容的提问来源于stack exchange,提问作者Srishty Mandal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:22:33