首页 > 解决方案 > 使用 webpack 在 Django 服务器上运行 React App 的问题

问题描述

我正在使用 Django 作为后端构建一个 Web 应用程序,并希望实现一个 ReactJS 框架前端。我现在拥有的每个应用程序都可以正常运行,彼此独立。我还实现了 webpack,它似乎配置正确,因为它将在 localhost 上运行我的 ReactJS 应用程序。作为 webpack 的新手(以及一般的 web 开发),我不确定如何让 React 在 Django 本地服务器(127.0.0.1:8000)上运行。我从阅读过的许多论坛中了解到,需要捆绑 javascript 文件,然后将其读入 django 应用程序。以下是相关文件:

包.json

{
  "name": "package.json",
  "version": "1.0.0",
  "description": "This is the private repository for the USA Baseball analytics team.",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "SET NODE_ENV=development babel src -d lib",
    "build-prod": "SET NODE_ENV=development babel src -d lib",
    "start": "webpack-dev-server"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/USAB-Analytics/BaldEagle.git"
  },
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/USAB-Analytics/BaldEagle/issues"
  },
  "homepage": "https://github.com/USAB-Analytics/BaldEagle#readme",
  "dependencies": {
    "react": "^16.2.0",
    "express": "^4.16.3",
    "react-dom": "^16.4.1",
    "react-sortable-hoc": "^0.8.3",
    "yarn": "^1.7.0",
    "react-prop-types": "^0.4.0",
    "semantic-ui-react": "^0.77.1",
    "react-router-dom": "^4.2.2"
  },
  "devDependencies": {
    "babel": "^6.23.0",
    "babel-core": "^6.26.3",
    "babel-loader": "^7.1.4",
    "babel-preset-env": "^1.6.1",
    "babel-preset-stage-1": "^6.24.1",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "html-webpack-plugin": "3.0.4",
    "style-loader": "^0.19.1",
    "css-loader": "^0.28.10",
    "jsx-loader": "^0.13.2",
    "react": "^16.4.0",
    "webpack": "^4.10.2",
    "webpack-bundle-tracker": "^0.3.0",
    "webpack-cli": "^3.0.4",
    "webpack-command": "^0.2.1",
    "webpack-dev-server": "^3.1.4"
  },
  "keywords": []
}

webpack.config.js

var path = require("path");
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
//var BundleTracker = require('webpack-bundle-tracker')

const port = process.env.PORT || 3000;

process.env.NODE_ENV = 'production';

module.exports = {
 mode: 'development',
 entry: './frontend/src/index.js',
 output: {
   filename: 'bundle.[hash].js'
 },
 devtool: 'inline-source-map',

 module: {
   rules: [

     // First Rule
     {
       test: /\.(js)$/,
       exclude: /node_modules/,
       use: ['babel-loader']
     },

     // Second Rule
     {
       test: /\.css$/,
       use: [
         {
           loader: 'style-loader'
         },
         {
           loader: 'css-loader',
           options: {
             modules: true,
             camelCase: true,
             sourceMap: true
           }
         }
       ]
     }
   ]
 },
 plugins: [
   new HtmlWebpackPlugin({
     title: 'Custom template',
     template: './webapp/templates/webapp/home.html',
   })
 ],
 devServer: {
   host: 'localhost',
   port: port,
   historyApiFallback: true,
   open: true
 }

};

前端/src/index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './css/main.css';
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";

import {HomePage} from './components/HomePage.js'
import {Bios} from './components/Bios.js'
import {Bio} from './components/Bio.js'
import {NavBar} from './components/NavBar.js'
import {TeamsList} from './components/TeamsList.js'
import {TOSBios} from './components/TOSBios.js'
import {NT18Bios} from './components/NT18Bios.js'
import {CNTBios} from './components/CNTBios.js'
import {NT15Bios} from './components/NT15Bios.js'

class App extends React.Component {
  render(){
    var styles = {
      'marginLeft': '210px'
    }
    return (
      <Router>
        <div className="col-sm-10">
          <NavBar />
            <div style={styles}>
            <Switch>
              <Route exact path="/" component={HomePage} />
              <Route path="/bios/:id" component={Bio} />
              <Route path="/bios/" component={Bios} />
              <Route path="/teams/tos/:id" component={Bio} />
              <Route path="/teams/cnt/:id" component={Bio} />
              <Route path="/teams/nt18/:id" component={Bio} />
              <Route path="/teams/nt15/:id" component={Bio} />
              <Route path="/teams/cnt/" component={CNTBios} />
              <Route path="/teams/nt18/" component={NT18Bios} />
              <Route path="/teams/nt15/" component={NT15Bios} />
              <Route path="/teams/tos/" component={TOSBios} />
              <Route path="/teams/" component={TeamsList} />
            </Switch>
            </div>
        </div>
      </Router>
    );
  }
}


ReactDOM.render(
    <App />,
  document.getElementById('root')
);

webapp/模板/webapp/home.html

<!-- {% extends "webapp/header.html" %} -->
{% load render_bundle from webpack_loader %}
<html>
<head>
    <meta charset="UTF-8">
    <title>React with Django</title>
</head>

<body>
    <div id="root"></div>
</body>
</html>

标签: javascriptdjangoreactjswebpackdjango-middleware

解决方案


您已将 webpack 配置为开发模式。这意味着您运行 webpack 开发服务器。但是您需要将前端应用程序构建成一个包,然后将此包用于您的服务器端。只需删除该devServer部分。此外,您可以删除它process.env.NODE_ENV = 'production';并将其更改modeproduction. 此操作会将您设置process.env.NODE_ENVproduction( https://webpack.js.org/concepts/mode/ )。

如果您需要在开发模式下测试您的应用程序,您可以将proxy您的后端地址添加到 package.json 中,并分别前后运行。

解决方案:

添加一个 npm 命令: "build:prod": "<your_build_command> && mv <output_path>/index.html <path_to_backend>/<app_name>/templates && mv <output_path>/* <path_to_backend>/static"

将此添加到您的 Django 应用程序设置中:

STATIC_URL = '/static/'
STATICFILES_DIRS = (
  os.path.join(BASE_DIR, 'static'),
)

推荐阅读