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

如何在XAMPP中通过index.php运行create-react-app创建的React应用?

兄弟,我完全懂你现在的痛点——折腾了一周想把React+PHP在XAMPP上凑一起,要么是webpack只适配纯HTML,要么是教程全用Node服务器,根本找不到贴合你需求的方案。别慌,我给你一套实操性拉满的解决办法:

1. 用Vite替代Webpack,快速搭建支持组件导入的React环境

手动配置Webpack确实麻烦,不如用Vite来简化流程,它能完美支持组件导入、第三方库(比如MDBootstrap),还能直接编译出静态资源供PHP加载:

  • 先在本地初始化一个Vite React项目:
    npm create vite@latest my-react-app -- --template react
    
  • 进入项目目录安装依赖:
    cd my-react-app && npm install
    
  • 安装MDBootstrap React组件库(按你的需求):
    npm install mdb-react-ui-kit
    
    记得按照MDB的文档在src/main.jsx里导入全局样式,比如:
    import 'mdb-react-ui-kit/dist/css/mdb.min.css';
    
  • 正常开发你的React组件,比如在App.jsx里使用MDB的按钮:
    import { MDBBtn } from 'mdb-react-ui-kit';
    
    function App() {
      return (
        <div>
          <MDBBtn color="primary">点击我</MDBBtn>
        </div>
      );
    }
    
    export default App;
    
  • 编译项目生成静态资源:
    npm run build
    
    这时候会得到一个dist文件夹,里面是编译好的JS、CSS和资源文件。

2. 整合到XAMPP的PHP项目结构

把dist文件夹里的所有内容,复制到你的XAMPP项目目录下,比如Website/react_app/dist/。然后修改你的index.php,让它加载这些静态资源:

  • 在<head>标签里引入编译后的CSS文件(注意替换成实际的哈希文件名):
    <link rel="stylesheet" href="react_app/dist/assets/index-xxxxxx.css">
    
  • 在<body>里添加React挂载的根节点,然后引入编译后的JS文件:
    <div id="root"></div>
    <script type="module" src="react_app/dist/assets/index-xxxxxx.js"></script>
    
    这样访问http://localhost/Website/index.php时,PHP页面就会加载并运行你的React应用,组件导入、MDB组件都能正常工作。

3. 解决React与PHP后端的交互问题

如果你的React应用需要调用PHP接口,直接用fetch或者Axios请求本地的PHP文件即可,比如:

// 在React组件中调用PHP接口
fetch('../api/get-user-data.php')
  .then(response => response.json())
  .then(data => {
    console.log(data);
    // 处理返回的数据
  })
  .catch(error => console.error('请求失败:', error));

只要XAMPP的Apache服务正常运行,就能无缝对接。

4. 开发阶段的便捷技巧

不想每次修改React代码都重新编译?可以在Vite的配置文件vite.config.js里设置代理,把API请求转发到XAMPP服务器:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [react()],
  server: {
    proxy: {
      '/api': {
        target: 'http://localhost/Website/', // 你的XAMPP项目根地址
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '')
      }
    }
  }
});

这样开发时用npm run dev启动Vite的开发服务器,既能实时预览React的修改,又能正常调用XAMPP里的PHP接口,开发效率拉满。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 19:42:51