简体   繁体   English

使用Webpack在Django服务器上运行React App的问题

[英]Issue running React App on Django server with webpack

I am building a web-application using Django as the backend and want to implement a ReactJS framework frontend. 我正在使用Django作为后端构建Web应用程序,并想实现ReactJS框架前端。 Each application that I have as of now runs properly, independently of one another. 到目前为止,我拥有的每个应用程序都可以正常运行,彼此独立。 I have also implemented webpack and it appears to configure properly, as it will run my ReactJS application on the localhost. 我还实现了webpack,它似乎配置正确,因为它将在本地主机上运行我的ReactJS应用程序。 Being new to webpack (and web-development in general) I am unsure how to get React to run on the Django local server (127.0.0.1:8000). 作为webpack的新手(和一般来说是Web开发),我不确定如何使React在Django本地服务器上运行(127.0.0.1:8000)。 I understand from the many forums I've read through that the javascript files need to be bundled and then read into the django app. 我在许多论坛上都了解到,需要将javascript文件捆绑在一起,然后再读入django应用程序。 Below are the relevant files: 以下是相关文件:

package.json package.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 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
 }

};

frontend/src/index.js frontend / 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/templates/webapp/home.html webapp / templates / 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>

These shouldn't be running on the same server. 这些不应在同一服务器上运行。 If you are looking to connect them you should be able to create config files and say if production the url I hit is xx.com/users otherwise if it is development it is localhost:8000/users. 如果您希望连接它们,则应该能够创建配置文件,并说出生产版本,我命中的URL是xx.com/users,否则,如果正在开发中,则是localhost:8000 / users。 Why would you need both to run on the same server? 为什么您需要两者都在同一服务器上运行?

我们使用django-webpack-loader在django模板中呈现我们的webpack捆绑包(对于Vue应用程序,但这是相同的基本思想)。

You've configured your webpack for development mode. 您已将Webpack配置为开发模式。 It means that you run the webpack development server. 这意味着您运行了webpack开发服务器。 But you need to build your front-end application into a bundle and then use this bundle for your server side. 但是,您需要将前端应用程序构建为捆绑软件,然后将此捆绑软件用于服务器端。 Just remove the devServer section. 只需删除devServer部分。 Also, you can erase this process.env.NODE_ENV = 'production'; 另外,您可以删除此process.env.NODE_ENV = 'production'; and change the mode to production . 并将mode更改为production This operation will set your process.env.NODE_ENV to production ( https://webpack.js.org/concepts/mode/ ). 此操作会将您的process.env.NODE_ENV设置为productionhttps://webpack.js.org/concepts/mode/ )。

If you need to test your app in development mode you can add proxy to package.json with the address of your back-end and run front and back separately. 如果您需要在开发模式下测试您的应用程序,则可以使用后端地址将proxy添加到package.json,并前后运行。

Solution: 解:

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

Add this to your Django app settings: 将此添加到您的Django应用设置中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM