如何在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:
- First, build your React SPA for production using
npm run build(oryarn buildif you use Yarn). This generates abuildfolder with all static assets (HTML, CSS, JS, images). - You can host these assets directly in your custom Drupal module or Drupal’s
sites/default/filesdirectory. For simplicity, let’s place them in a subfolder of your custom module:modules/custom/react_integration/react_app/build.
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
- Go to Drupal’s Extend page (
/admin/modules), find yourreact_integrationmodule, and enable it. - Clear Drupal’s cache (use
/admin/config/development/performanceor rundrush crvia the command line). - Visit the URL you defined (
/react-app)—your React SPA should load and mount into the#rootdiv!
- Development Mode: For hot reloading during React development, skip building for production. Instead, set
"proxy": "http://your-drupal-site.local"in your React app’spackage.json, then in your controller, add a script tag pointing tohttp://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:
Access it in React via// In your controller's content() method $build['#attached']['drupalSettings']['react_integration']['user'] = [ 'name' => $this->currentUser()->getDisplayName(), 'id' => $this->currentUser()->id(), ];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
fetchor Axios.
内容的提问来源于stack exchange,提问作者Srishty Mandal

