[django]有没有办法将 Django 与 Next.js 集成?
· 收录于 2024-01-06 14:10:08 · source URL
问题详情
我已经通过访问 build/index.html
的功能将 Reactjs 与 Django 集成在一起。下面的代码显示了我是如何做到这一点的。
config/urls.py
urlpatterns = [
...
re_path(r'search/', react_views.ReactAppView.as_view()),
]
PROJECT_NAME/视图.py
class ReactAppView(View):
def get(self, request):
try:
with open(os.path.join(str(settings.BASE_DIR), 'frontend', 'build', 'index.html')) as file:
return HttpResponse(file.read())
except:
return HttpResponse(
"""
Build your React app.
""",
status=501,
)
ReactAppView
函数访问在 React 端使用 yarn build
创建的 index.html
。基本上,我只将 React 用于搜索视图,除了搜索视图之外,我还使用了 jQuery,因为它首先是用 jQuery 开发的。
自从我发现我需要 Next.js 才能将服务器端渲染 (SSR) 与 React 一起使用以来,我一直在尝试将 React 应用程序迁移到 Next.js。但是,Next.js 没有 index.html
。它只有页面/index.js
。
我非常努力地弄清楚如何将 Django 与 Next.js 集成,但我找不到任何有用的资源。谁能帮我解决这个问题?
最佳回答
似乎您想提供静态文件(即 React 或 Next.js 包)。
Django 有一个关于如何做到这一点的指南(通过 django.contrib.staticfiles
)
最简单的例子(直接来自文档)是:
-
设置
STATIC_FILES
文件夹:STATIC_URL = '/static/'
-
将
index.html
文件放在那里,并将其引用为/static/index.html
。
关于staticfiles
的更多信息,请参考官方文档:https://docs.djangoproject.com/en/4.0/howto/static-files/
在 Next.js 端,您需要遵循 https://nextjs.org/docs/advanced-features/static-html-export 或者手动创建一个索引.html
其中包含您正在使用的所有 next.js 捆绑包。