Skip to main content

Hướng dẫn sử dụng React vào module Drupal 9

Có lẻ bạn đã biết Drupal là một CMS, và React là JavaScript Framework là nền cảng sử dụng khá phổ biến hiện nay, trong hướng dẫn này, chúng ta sẽ tạo module React  Example Module là một module drupal nhưng được nhúng React vào trong nó.

Khởi tạo module React Examle Module

1. Khai báo module drupal - tạo file drupal9/modules/react_example_module/react_example_module.info.yml

name: React Examle Module
type: module
description: This is React Examle Module
core_version_requirement: ^8 || ^9
core: 8.x
package:Custom module

2. Khởi tạo route /react-example-module để chúng ta nhúng React vào trang này.

Tạo file drupal9/modules/react_example_module/react_example_module.routing.yml

react_example_module._form:
  path: '/react-example-module'
  defaults:
    _controller: '\Drupal\react_example_module\Controller\ReactExampleController::get_form'
    _title: 'React Example Module'
  requirements:
    _permission: 'access content'

3. Tạo file thư viện js và css, chúng ta tạo file drupal9/modules/react_example_module/react_example_module.libraries.yml

react_app:
  version: VERSION
  js:
    reactjs/js/dist/main.min.js: { minified: true }

react_app_dev:
  version: VERSION
  js:
    reactjs/js/dist_dev/main.min.js: {minified: true}

4. Tạo file controller - drupal9\modules\react_example_module\src\Controller\ReactExampleController.php

<?php

namespace Drupal\react_example_module\Controller;

use Drupal\Core\Controller\ControllerBase;

/**
 * Class ReatExampleController.
 *
 * @package Drupal\react_example_module\Controller
 */
class ReatExampleController extends ControllerBase {

  /**
   * Form.
   * @return string 
   */
  public function get_form_calculator() {

    if (file_exists(__DIR__ . '../../../reactjs/js/dist_dev')) {
      $library = 'react_example_module/react_app_dev';
    }else{
      $library =  'react_example_module/react_app';
    }
    return [
        '#type' => 'markup',
        '#markup' => '<div id="root"></div>',
        '#attached' => [
            'library' =>  [
              $library ,
            ],
        ],
    ];
  }

}

Trong đó, đoạn code này để xử lý chọn nhúng thư viện react trong môi trường dev hay trong môi trường prod

if (file_exists(__DIR__ . '../../../reactjs/js/dist_dev')) {
      $library = 'react_example_module/react_app_dev';
    }else{
      $library =  'react_example_module/react_app';
   }

Khởi tạo React bên trong module

1. Tạo project React

Tại vị trí của module và chạy lệnh 

npx create-react-app reactjs

2. Cài đặt thêm các package bạn cần

#trỏ vào thư mục reactjs vừa tạo
cd reactjs

# cài đặt react, react-dom
npm install react react-dom

#cài đặt các dev dependencies
npm install --save-dev @babel/core @babel/cli @babel/preset-env @babel/preset-react babel-loader webpack webpack-cli

Bạn có thể tham khảo thông tin về package ở đây

Package name

ID

Description

Dependency Type

Babel Core

@babel/core

Babel là một trình chuyển đổi JavaScript có thể chuyển đổi JavaScript mà bạn viết (ví dụ: React) thành JavaScript có thể chạy trong bất kỳ trình duyệt nào.

dev

Babel CLI

@babel/cli

Gói CLI cho Babel.

dev

Babel Preset Env

@babel/preset-env

Gói chuyển đổi JavaScript Babel cơ bản

dev

Babel Preset React

@babel/preset-react

Chuyển đổi Babel cho React JavaScript

dev

Babel Loader

babel-loader

Cho phép gói web sử dụng Babel làm trình chuyển tiếp.

dev

Webpack

webpack

Một công cụ để đóng gói JavaScript để trình duyệt có thể sử dụng nó.

dev

Webpack CLI

webpack-cli

Cho phép npm chạy các lệnh webpack

dev

React

react

Thư viện JavaScript của React

prod

React Dom

react-dom

The entry point to the DOM for React

prod

  3. Tạo config Webpack - Tạo file reactjs/webpack.config.js

const path = require('path');
const isDevMode = process.env.NODE_ENV !== 'production';

const config = {
  entry: {
    main: ["./src/index.js"]
  },
  devtool: (isDevMode) ? 'source-map' : false,
  mode: (isDevMode) ? 'development' : 'production',
  output: {
    path: isDevMode ? path.resolve(__dirname, "js/dist_dev") : path.resolve(__dirname, "js/dist"),
    filename: '[name].min.js'
  },
  
  resolve: {
    extensions: ['.js', '.jsx'],
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          'style-loader',
          'css-loader'
        ]
      },
      {
        test: /\.svg$/,
        use: "file-loader",
      },
      {
        test: /\.js$/,
        exclude: /(node_modules)/,
        use: {
          loader: 'babel-loader'
        }
      }
    ]
    
  },
};

module.exports = config;

Webpack.config.js này sử dụng biến isDevMode để sửa đổi cấu hình vào việc bạn đang chạy ở chế độ "dev" hay chế độ "prod".

Đối với chế độ "dev", chúng tôi thay đổi thư mục đầu ra nơi các tệp đã biên dịch được lưu vào react_example_module/js/dist_dev.

Sau đó, chúng tôi thêm thư mục đó vào tệp .gitignore của chúng tôi để đảm bảo nội dung phát triển không bao giờ được commit git. Điều này không bắt buộc, nhưng đó là một ý tưởng hay.

 4. Khởi tạo script trong package

Thay thế đoạn script vào trong package.json

  "main": "./src/index.js",
  "scripts": {
    "build": "NODE_ENV=production webpack",
    "build:dev": "webpack",
    "start": "webpack --watch"
  },

5. Enable module React Example React

Enabale module React Example React và ở link: http://example.com/react-example-module để thấy React đã nhúng vào Drupal.

Image
React Example React

Link Github: https://github.com/nguyenphudung93dn/React-Example-Module/ 

Tham Khảo:

  • https://www.mediacurrent.com/blog/recipe-embedded-react-component-drupal
  • https://drupalize.me/tutorial/connect-react-drupal-theme-or-module?p=3253