Django、Create-react-app、Heroku

标签 django reactjs heroku create-react-app

我的 Django Web 应用程序中有 3 个文件夹。这些文件夹如下:包含settings.py(project)的文件夹、包含models.py(application)的文件夹以及包含由create-react-app创建的前端react应用程序的文件夹。

我想构建 React 前端,将构建工件复制到静态文件夹中,然后在 Heroku 上运行 django 应用程序,但他们使这个过程在我当前的文件夹结构中几乎不可能实现。另一种方法是压平 React 应用程序,并将 build、src、node_modules、packagejson 等全部放在项目的根目录中,但这看起来真的很糟糕。

settings.py 中的一些配置:

STATICFILES_DIRS = (
os.path.join(PROJECT_ROOT, 'static'),
os.path.join(BASE_DIR, 'front-end/build/static')

)

我在前端本地运行的内容:

npm run build

我从 View 中返回的内容:

def index(request):

    return HttpResponse(loader.get_template('build/index.html').render())
    #above line returns index.html that is generated by npm run build

如何将上述项目部署到 Heroku 以便它可以找到所有静态资源?

最佳答案

您可以使用 symlink将 React 的构建输出放入 django 目录的链接

例如,如果您的目录结构是这样的:

~/project_root/
~/project_root/django/static/
~/project_root/my_react_app/build

cd 到 ~/project_root/django/static/ 并运行

ln -s ../../my_react_app/build .

这将创建指向 ~/project_root/my_react_app/build~/project_root/django/static/build

关于Django、Create-react-app、Heroku,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43711556/

相关文章:

python - 如何在python中链接一个css文件

javascript - 如何在一个按钮中放置两个图标

javascript - 如何在heroku服务器目录上创建csv文件?

heroku - x509 : certificate signed by unknown authority

django - 如何从 drf-spectacular API 文档中删除 RetrieveUpdateAPIView 中的 put 方法?

django - 将来自不同应用程序/对象的模型分组到一个管理 block 中

javascript - 当我使用路由显示 Web 应用程序页面时,如何为模板标签添加 HTML 页面

javascript - 如何在特定节点上安装嵌套的 react 组件?

ruby-on-rails - 带 Letsencrypt 的 Heroku - 无法使用插件

html - 关于for循环(循环模板)