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

无法集成django_vite:Django+React项目导入函数组件报错求助

Django + React + Vite 集成组件导入报错问题

环境配置

  • Django 5.0.6
  • React 18.2.0
  • Vite 5.1.6
  • @vitejs/plugin-react 4.2.1

问题说明

搭建极简项目时,尝试用django_vite整合Django与React,遇到核心问题:只要在main.jsx中导入函数式组件,就会触发报错(报错截图:报错截图)。曾尝试改用django_vite_plugin集成,仍出现相同错误;若不导入组件,直接将所有代码写在main.jsx中则可正常运行,但这并非理想开发模式。

相关配置文件内容

package.json

{
  "dependencies": {
    "vite": "^5.1.6",
    "@vitejs/plugin-react": "^4.2.1",
    "antd": "^5.17.0",
    "axios": "^1.6.8",
    "bootstrap": "^5.3.3",
    "exif-js": "^2.3.0",
    "exifr": "^7.1.3",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router-dom": "^6.22.3",
    "react-toastify": "^10.0.5"
  },
  "devDependencies": {
    "@types/react": "^18.2.64",
    "@types/react-dom": "^18.2.21",
    "eslint": "^8.57.0",
    "eslint-config-airbnb": "^19.0.4",
    "eslint-plugin-import": "^2.29.1",
    "eslint-plugin-jsx-a11y": "^6.8.0",
    "eslint-plugin-react": "^7.34.1",
    "eslint-plugin-react-hooks": "^4.6.2",
    "eslint-plugin-react-refresh": "^0.4.5"
  }
}

settings.py

STATIC_URL = 'static/'
STATIC_ROOT = 'staticfiles/'
STATICFILES_DIR = [
    BASE_DIR / 'dist'
]

DJANGO_VITE = {
    "default": {
        "dev_mode": DEBUG
    }
}

vite.config.js

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

export default defineConfig({  
  base:'/static/',
  build:{
    emptyOutDir:true,
    manifest:'manifest.json',
    assetsDir:'',
    outDir:'./dist',
    rollupOptions:{
      input:{
        home:"./frontend/main.jsx"
      }
    }
  },
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './frontend'),
      '@styles': path.resolve(__dirname, './frontend/assets/styles'),
    },
  },
  plugins: [react()],
});

home.html

{% load django_vite %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    {% vite_hmr_client %}
    {% vite_asset './frontend/main.jsx' %}
    <title>Document</title>
</head>
<body>
    <div id="app">
    </div>
</body>
</html>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 02:20:00