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

时间:2018-12-10 15:21:24

标签: django reactjs nginx webpack

我正在关注本教程:

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 /乘客

我已经按照说明安装了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'),
        }
}

frontend / 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"
  }
}

frontend / 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 /乘客配置:

/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 个答案:

答案 0 :(得分: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页面并将其移动到项目根目录中的资产文件夹中:

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。