如何在 Ubuntu 服务器上使用 create-react-app 使用 Webpack/React 配置 Django

Posted

技术标签:

【中文标题】如何在 Ubuntu 服务器上使用 create-react-app 使用 Webpack/React 配置 Django【英文标题】:How to configure Django with Webpack/React using create-react-app on Ubuntu server 【发布时间】:2019-05-11 12:41:12 【问题描述】:

我正在学习本教程:

http://v1k45.com/blog/modern-django-part-1-setting-up-django-and-react/

本教程描述了如何使用 webpack 设置 Django/React 应用程序。

在我的开发机器上一切正常,但远程服务器(Ubuntu 16.04.4)上的静态文件有问题。

这些是我的问题:

1) 为什么我的开发版在 localhost 中寻找静态文件?

2) 如果我使用 nginx/Passenger 提供生产版本,即使链接看起来正确,静态文件也不会加载到浏览器中。这是为什么呢?

编辑:我想我已经找到了设置乘客的答案。即使 wsgi.py 加载应用程序,您也需要告诉 Nginx 静态文件的位置。我的工作 /etc/nginx/sites-enabled/ponynote.conf:

server 
    listen 80;
    server_name 178.62.85.245;

    passenger_python /var/www/ponynotetest/venv36/bin/python3.6;

    # Tell Nginx and Passenger where your app's 'public' directory is
    root /var/www/ponynotetest/ponynote/ponynote;

    location /static/ 
       autoindex on;
       alias /var/www/ponynotetest/ponynote/assets/;
    

    # Turn on Passenger
    passenger_enabled on;

3) 我需要为生产配置 STATIC_ROOT 并运行 collectstatic 吗?

非常感谢您的帮助!

这里有更多信息和代码:

为了确保我没有打错任何字,我克隆了源代码,切换到分支“part-1”并按照自述文件中的所有说明进行操作。

我在 settings.py ALLOWED_HOSTS 中添加了“xx.xx.xx.xx”,其中 xx.xx.xx.xx 是我的服务器的 IP 地址。

我在 frontend/package.json 中添加了 "proxy": "http://localhost:8000"。

1) 开发版

我正在运行开发服务器:

./manage.py 运行服务器 xx.xx.xx.xx:8000

在使用前端文件夹中的“npm run start”启动 webpack 服务器之前,我还运行了“npm run build”。

问题:当我在浏览器中导航到 xx.xx.xx.xx:8000 时,我看到一个空白页面。这是 html

<html><head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width">
    <title>Ponynote</title>
  </head>
  <body>
    <div id="root">
    </div>
      <script type="text/javascript" src="http://localhost:3000/static/js/bundle.js"></script>
  </body></html>

在我看来,该页面似乎正在尝试在 localhost 上查找 bundle.js - 我认为它应该在服务器上的相对路径上查找。我想这就是为什么我在本地机器上运行代码而不是在服务器上运行代码的原因。

我在 Django 或 Webpack 中找不到将位置指定为 localhost 的内容。我错过了一个设置还是出于某种原因这不可能?

2) Nginx/Passenger

我已经按照说明安装了 Nginx 和Passenger:

https://www.phusionpassenger.com/library/walkthroughs/deploy/python/digital_ocean/nginx/oss/xenial/deploy_app.html#edit-nginx-configuration-file

在 xx.xx.xx.xx,浏览器显示的 html 看起来是正确的,但文件没有被加载。请参阅下面由 Nginx 提供的 html。请注意,静态链接显示正确的相对 URL,与在生产模式下运行 Django 服务器时完全相同,但不在端口 8000 上,但文件本身并未加载。

/var/log/nginx/error.log 没有显示任何错误。

<html><head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width">
    <title>Ponynote</title>
  </head>
  <body>
    <div id="root">
    </div>
      <script type="text/javascript" src="/static/bundles/js/main.a416835a.js"></script>
<link type="text/css" href="/static/bundles/css/main.c17080f1.css" rel="stylesheet">
  </body></html>

3) 以生产模式运行的 Django 服务器

如果我使用以下命令在生产模式下运行 Django 服务器:

./manage.py runserver --settings=ponynote.production_settings 178.62.85.245:8000

即使我没有运行 collectstatic,该页面在 xx.xx.xx.xx:8000 的浏览器中看起来也不错。该教程说运行 collectstatic 但如果您尝试会显示错误:“您正在使用 staticfiles 应用程序而没有将 STATIC_ROOT 设置设置为文件系统路径”。不知道是需要在production_settings.py中设置STATIC_ROOT,还是不需要运行collectstatic?

这是我的设置文件:

ponynote/templates/index.html

% load render_bundle from webpack_loader %
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width" />
    <title>Ponynote</title>
  </head>
  <body>
    <div id="root">
    </div>
      % render_bundle 'main' %
  </body>
</html>

ponynote/settings.py

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '=e%s=1kdk1_+yur9cmpkw8r-z5gd(owqpxbyl+6^)*10-a3c4v'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['xx.xx.xx.xx']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'webpack_loader',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'ponynote.urls'

TEMPLATES = [
    
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, "templates"), ],
        'APP_DIRS': True,
        'OPTIONS': 
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        ,
    ,
]

WSGI_APPLICATION = 'ponynote.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases

DATABASES = 
    'default': 
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    



# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    ,
    
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    ,
    
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    ,
    
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    ,
]


# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

STATIC_URL = '/static/'


WEBPACK_LOADER = 
    'DEFAULT': 
            'BUNDLE_DIR_NAME': 'bundles/',
            'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.dev.json'),
        

前端/package.json


  "name": "frontend",
  "version": "0.1.0",
  "private": true,
  "dependencies": 
    "autoprefixer": "7.1.2",
    "babel-core": "6.25.0",
    "babel-eslint": "7.2.3",
    "babel-jest": "20.0.3",
    "babel-loader": "7.1.1",
    "babel-preset-react-app": "^3.0.3",
    "babel-runtime": "6.26.0",
    "case-sensitive-paths-webpack-plugin": "2.1.1",
    "chalk": "1.1.3",
    "css-loader": "0.28.4",
    "dotenv": "4.0.0",
    "eslint": "4.4.1",
    "eslint-config-react-app": "^2.0.1",
    "eslint-loader": "1.9.0",
    "eslint-plugin-flowtype": "2.35.0",
    "eslint-plugin-import": "2.7.0",
    "eslint-plugin-jsx-a11y": "5.1.1",
    "eslint-plugin-react": "7.1.0",
    "extract-text-webpack-plugin": "3.0.0",
    "file-loader": "0.11.2",
    "fs-extra": "3.0.1",
    "html-webpack-plugin": "2.29.0",
    "jest": "20.0.4",
    "object-assign": "4.1.1",
    "postcss-flexbugs-fixes": "3.2.0",
    "postcss-loader": "2.0.6",
    "promise": "8.0.1",
    "react": "^16.0.0",
    "react-dev-utils": "^4.1.0",
    "react-dom": "^16.0.0",
    "style-loader": "0.18.2",
    "sw-precache-webpack-plugin": "0.11.4",
    "url-loader": "0.5.9",
    "webpack": "3.5.1",
    "webpack-dev-server": "2.8.2",
    "webpack-manifest-plugin": "1.2.1",
    "whatwg-fetch": "2.0.3"
  ,
  "scripts": 
    "start": "node scripts/start.js",
    "build": "node scripts/build.js",
    "test": "node scripts/test.js --env=jsdom"
  ,
  "jest": 
    "collectCoverageFrom": [
      "src/**/*.js,jsx"
    ],
    "setupFiles": [
      "<rootDir>/config/polyfills.js"
    ],
    "testMatch": [
      "<rootDir>/src/**/__tests__/**/*.js?(x)",
      "<rootDir>/src/**/?(*.)(spec|test).js?(x)"
    ],
    "testEnvironment": "node",
    "testURL": "http://localhost",
    "transform": 
      "^.+\\.(js|jsx)$": "<rootDir>/node_modules/babel-jest",
      "^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
      "^(?!.*\\.(js|jsx|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
    ,
    "transformIgnorePatterns": [
      "[/\\\\]node_modules[/\\\\].+\\.(js|jsx)$"
    ],
    "moduleNameMapper": 
      "^react-native$": "react-native-web"
    ,
    "moduleFileExtensions": [
      "web.js",
      "js",
      "json",
      "web.jsx",
      "jsx",
      "node"
    ]
  ,
  "babel": 
    "presets": [
      "react-app"
    ]
  ,
  "eslintConfig": 
    "extends": "react-app"
  ,
  "proxy": "http://localhost:8000",
  "devDependencies": 
    "webpack-bundle-tracker": "^0.2.0"
  

前端/config/webpack.config.dev.js

'use strict';

const autoprefixer = require('autoprefixer');
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
const eslintFormatter = require('react-dev-utils/eslintFormatter');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
const getClientEnvironment = require('./env');
const paths = require('./paths');
const BundleTracker = require('webpack-bundle-tracker');


// Webpack uses `publicPath` to determine where the app is being served from.
// In development, we always serve from the root. This makes config easier.
const publicPath = 'http://localhost:3000/';
// `publicUrl` is just like `publicPath`, but we will provide it to our app
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
// Omit trailing slash as %PUBLIC_PATH%/xyz looks better than %PUBLIC_PATH%xyz.
const publicUrl = 'http://localhost:3000/';
// Get environment variables to inject into our app.
const env = getClientEnvironment(publicUrl);

// This is the development configuration.
// It is focused on developer experience and fast rebuilds.
// The production configuration is different and lives in a separate file.
module.exports = 
  // You may want 'eval' instead if you prefer to see the compiled output in DevTools.
  // See the discussion in https://github.com/facebookincubator/create-react-app/issues/343.
  devtool: 'cheap-module-source-map',
  // These are the "entry points" to our application.
  // This means they will be the "root" imports that are included in JS bundle.
  // The first two entry points enable "hot" CSS and auto-refreshes for JS.
  entry: [
    // We ship a few polyfills by default:
    require.resolve('./polyfills'),
    // Include an alternative client for WebpackDevServer. A client's job is to
    // connect to WebpackDevServer by a socket and get notified about changes.
    // When you save a file, the client will either apply hot updates (in case
    // of CSS changes), or refresh the page (in case of JS changes). When you
    // make a syntax error, this client will display a syntax error overlay.
    // Note: instead of the default WebpackDevServer client, we use a custom one
    // to bring better experience for Create React App users. You can replace
    // the line below with these two lines if you prefer the stock client:
    require.resolve('webpack-dev-server/client') + '?http://localhost:3000',
    require.resolve('webpack/hot/dev-server'),
    // require.resolve('react-dev-utils/webpackHotDevClient'),
    // Finally, this is your app's code:
    paths.appIndexJs,
    // We include the app code last so that if there is a runtime error during
    // initialization, it doesn't blow up the WebpackDevServer client, and
    // changing JS code would still trigger a refresh.
  ],
  output: 
    // Next line is not used in dev but WebpackDevServer crashes without it:
    path: paths.appBuild,
    // Add /* filename */ comments to generated require()s in the output.
    pathinfo: true,
    // This does not produce a real file. It's just the virtual path that is
    // served by WebpackDevServer in development. This is the JS bundle
    // containing code from all our entry points, and the Webpack runtime.
    filename: 'static/js/bundle.js',
    // There are also additional JS chunk files if you use code splitting.
    chunkFilename: 'static/js/[name].chunk.js',
    // This is the URL that app is served from. We use "/" in development.
    publicPath: publicPath,
    // Point sourcemap entries to original disk location (format as URL on Windows)
    devtoolModuleFilenameTemplate: info =>
      path.resolve(info.absoluteResourcePath).replace(/\\/g, '/'),
  ,
  resolve: 
    // This allows you to set a fallback for where Webpack should look for modules.
    // We placed these paths second because we want `node_modules` to "win"
    // if there are any conflicts. This matches Node resolution mechanism.
    // https://github.com/facebookincubator/create-react-app/issues/253
    modules: ['node_modules', paths.appNodeModules].concat(
      // It is guaranteed to exist because we tweak it in `env.js`
      process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
    ),
    // These are the reasonable defaults supported by the Node ecosystem.
    // We also include JSX as a common component filename extension to support
    // some tools, although we do not recommend using it, see:
    // https://github.com/facebookincubator/create-react-app/issues/290
    // `web` extension prefixes have been added for better support
    // for React Native Web.
    extensions: ['.web.js', '.js', '.json', '.web.jsx', '.jsx'],
    alias: 

      // Support React Native Web
      // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
      'react-native': 'react-native-web',
    ,
    plugins: [
      // Prevents users from importing files from outside of src/ (or node_modules/).
      // This often causes confusion because we only process files within src/ with babel.
      // To fix this, we prevent you from importing files out of src/ -- if you'd like to,
      // please link the files into your node_modules/ and let module-resolution kick in.
      // Make sure your source files are compiled, as they will not be processed in any way.
      new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
    ],
  ,
  module: 
    strictExportPresence: true,
    rules: [
      // TODO: Disable require.ensure as it's not a standard language feature.
      // We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176.
      //  parser:  requireEnsure: false  ,

      // First, run the linter.
      // It's important to do this before Babel processes the JS.
      
        test: /\.(js|jsx)$/,
        enforce: 'pre',
        use: [
          
            options: 
              formatter: eslintFormatter,
              eslintPath: require.resolve('eslint'),

            ,
            loader: require.resolve('eslint-loader'),
          ,
        ],
        include: paths.appSrc,
      ,
      
        // "oneOf" will traverse all following loaders until one will
        // match the requirements. When no loader matches it will fall
        // back to the "file" loader at the end of the loader list.
        oneOf: [
          // "url" loader works like "file" loader except that it embeds assets
          // smaller than specified limit in bytes as data URLs to avoid requests.
          // A missing `test` is equivalent to a match.
          
            test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
            loader: require.resolve('url-loader'),
            options: 
              limit: 10000,
              name: 'static/media/[name].[hash:8].[ext]',
            ,
          ,
          // Process JS with Babel.
          
            test: /\.(js|jsx)$/,
            include: paths.appSrc,
            loader: require.resolve('babel-loader'),
            options: 

              // This is a feature of `babel-loader` for webpack (not Babel itself).
              // It enables caching results in ./node_modules/.cache/babel-loader/
              // directory for faster rebuilds.
              cacheDirectory: true,
            ,
          ,
          // "postcss" loader applies autoprefixer to our CSS.
          // "css" loader resolves paths in CSS and adds assets as dependencies.
          // "style" loader turns CSS into JS modules that inject <style> tags.
          // In production, we use a plugin to extract that CSS to a file, but
          // in development "style" loader enables hot editing of CSS.
          
            test: /\.css$/,
            use: [
              require.resolve('style-loader'),
              
                loader: require.resolve('css-loader'),
                options: 
                  importLoaders: 1,
                ,
              ,
              
                loader: require.resolve('postcss-loader'),
                options: 
                  // Necessary for external CSS imports to work
                  // https://github.com/facebookincubator/create-react-app/issues/2677
                  ident: 'postcss',
                  plugins: () => [
                    require('postcss-flexbugs-fixes'),
                    autoprefixer(
                      browsers: [
                        '>1%',
                        'last 4 versions',
                        'Firefox ESR',
                        'not ie < 9', // React doesn't support IE8 anyway
                      ],
                      flexbox: 'no-2009',
                    ),
                  ],
                ,
              ,
            ],
          ,
          // "file" loader makes sure those assets get served by WebpackDevServer.
          // When you `import` an asset, you get its (virtual) filename.
          // In production, they would get copied to the `build` folder.
          // This loader doesn't use a "test" so it will catch all modules
          // that fall through the other loaders.
          
            // Exclude `js` files to keep "css" loader working as it injects
            // it's runtime that would otherwise processed through "file" loader.
            // Also exclude `html` and `json` extensions so they get processed
            // by webpacks internal loaders.
            exclude: [/\.js$/, /\.html$/, /\.json$/],
            loader: require.resolve('file-loader'),
            options: 
              name: 'static/media/[name].[hash:8].[ext]',
            ,
          ,
        ],
      ,
      // ** STOP ** Are you adding a new loader?
      // Make sure to add the new loader(s) before the "file" loader.
    ],
  ,
  plugins: [
    // Makes some environment variables available in index.html.
    // The public URL is available as %PUBLIC_URL% in index.html, e.g.:
    // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    // In development, this will be an empty string.
    new InterpolateHtmlPlugin(env.raw),
    // Generates an `index.html` file with the <script> injected.
    new HtmlWebpackPlugin(
      inject: true,
      template: paths.appHtml,
    ),
    // Add module names to factory functions so they appear in browser profiler.
    new webpack.NamedModulesPlugin(),
    // Makes some environment variables available to the JS code, for example:
    // if (process.env.NODE_ENV === 'development')  ... . See `./env.js`.
    new webpack.DefinePlugin(env.stringified),
    // This is necessary to emit hot updates (currently CSS only):
    new webpack.HotModuleReplacementPlugin(),
    // Watcher doesn't work well if you mistype casing in a path so we use
    // a plugin that prints an error when you attempt to do this.
    // See https://github.com/facebookincubator/create-react-app/issues/240
    new CaseSensitivePathsPlugin(),
    // If you require a missing module and then `npm install` it, you still have
    // to restart the development server for Webpack to discover it. This plugin
    // makes the discovery automatic so you don't have to restart.
    // See https://github.com/facebookincubator/create-react-app/issues/186
    new WatchMissingNodeModulesPlugin(paths.appNodeModules),
    // Moment.js is an extremely popular library that bundles large locale files
    // by default due to how Webpack interprets its code. This is a practical
    // solution that requires the user to opt into importing specific locales.
    // https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
    // You can remove this if you don't use Moment.js:
    new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
    new BundleTracker(path: paths.statsRoot, filename: 'webpack-stats.dev.json'),
  ],
  // Some libraries import Node modules but don't use them in the browser.
  // Tell Webpack to provide empty mocks for them so importing them works.
  node: 
    dgram: 'empty',
    fs: 'empty',
    net: 'empty',
    tls: 'empty',
    child_process: 'empty',
  ,
  // Turn off performance hints during development because we don't do any
  // splitting or minification in interest of speed. These warnings become
  // cumbersome.
  performance: 
    hints: false,
  ,
;

Nginx/Passenger 配置:

/etc/nginx/sites-enabled/ponynote.conf

server 
    listen 80;
    server_name xx.xx.xx.xx;

    passenger_python /var/www/ponynote/venv36/bin/python3.6;

    # Tell Nginx and Passenger where your app's 'public' directory is
    root /var/www/ponynote/ponynote/ponynote;

    # Turn on Passenger
    passenger_enabled on;

passenger_wsgi.py

import ponynote.wsgi
application = ponynote.wsgi.application

ponynote/wsgi.py

import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ponynote.production_settings")
application = get_wsgi_application()

ponynote/production_settings.py

from .settings import *
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "assets"),
]

WEBPACK_LOADER = 
    'DEFAULT': 
            'BUNDLE_DIR_NAME': 'bundles/',
            'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.prod.json'),
        

【问题讨论】:

【参考方案1】:

如果脚本没有加载,并且当您在浏览器中访问脚本的 URL 时看到主页的 HTML,这意味着您的链接错误或 Nginx 没有提供文件。 (由于 URL 中没有文件,Nginx 会为您提供主页。)起初我没有意识到的是,虽然 Nginx 默认为 Django 应用程序提供服务,但它不提供任何不是的静态文件在“公共”文件夹中,因此不提供构建输出。

自从我遵循的教程编写以来,create-react-app 似乎也发生了变化;你现在似乎不需要做任何 webpack 配置。

最后,您需要将前端构建输出放在 Django 应用可以找到的位置。

较新的教程使我了解了一种在生产服务器上运行的方法: https://medium.com/alpha-coder/heres-a-dead-simple-react-django-setup-for-your-next-project-c0b0036663c6。我选择将前端保留在自己的文件夹中,并且我使用的是 Nginx/Passenger,所以我做了一些更改。

我是这样设置的。

1) 设置好 Django 项目后,在项目根文件夹中创建一个 React 应用:

create-react-app frontend

2) 告诉 Django 项目在哪里寻找 React 构建输出: 在 djangoproject/settings.py 中:

TEMPLATES = [
  
    ...
    'DIRS': [
      os.path.join(BASE_DIR, 'assets')
    ],
    ...
  
]

STATICFILES_DIRS = [
  os.path.join(BASE_DIR, 'assets/static'),
]

在 djangoproject/urls.py:

from django.contrib import admin
from django.urls import path, re_path
from django.views.generic import TemplateView

urlpatterns = [
  path('admin/', admin.site.urls),
  # path('api/', include('mynewapp.urls')),
  re_path('.*', TemplateView.as_view(template_name='index.html')),
]

在 frontend/src/index.js 的末尾添加这个以启用热重载:

if (module.hot) 
  module.hot.accept();

3) 在项目根目录中创建一个 bash 脚本来构建 React 页面并将它们移动到项目根目录中的 assets 文件夹中:

buildapp.sh
#!/usr/bin/env bash
npm run build --prefix frontend
rm -rf ./assets
mv ./frontend/build ./assets

运行此脚本。

4) 告诉 nginx 在哪里可以找到构建输出和正确的 Python 版本(假设您使用的是虚拟环境)。我正在使用Passenger来部署应用程序,因此此代码位于 sudo nano /etc/nginx/sites-enabled/myapp.conf 中

passenger_python /var/www/myapp/venv36/bin/python3.6;

# Tell Nginx where your app's 'public' directory is
root /var/www/myapp/myapp/myapp;

# Tell Nginx the location of the build output files
location /static/ 
   autoindex on;
   root /var/www/myapp/myapp/assets;

我还没有运行 collectstatic,一切看起来都很好。我猜您将来可能添加的任何其他资源只需要 collectstatic。

【讨论】:

我最近发现我确实需要运行 collectstatic,并提供收集的文件,才能添加一个网站图标。所以我必须更新根路径和位置路径以匹配。 我假设这意味着每次更改后都需要运行构建脚本。你如何处理这个以进行开发?每次要查看更改时运行脚本似乎有点麻烦。 我已经有一段时间没有看到这个了,但是 IIRC 正在开发中,更新由 webpack 为你处理。只有当您需要进行生产构建时,您的部署脚本才需要复制文件。 Nginx 只在我的生产服务器上运行,而不是我的开发机器上。

以上是关于如何在 Ubuntu 服务器上使用 create-react-app 使用 Webpack/React 配置 Django的主要内容,如果未能解决你的问题,请参考以下文章

如何为 conda create 指定新的环境位置

Postgres createdb 和 create database 在 Ubuntu 18.04 中不起作用

如何在Linux上使用tar命令解压和压缩文件

如何在本地 ubuntu14.04 上使用域名设置服务器?

如何在 Ubuntu上使用 Nginx 设置密码验证

如何在 Ubuntu上使用 Nginx 设置密码验证