Jay*_*Jay 4 django reactjs next.js
我通过具有访问build/index.html. 下面的代码显示了我是如何做到的。
配置/urls.py
urlpatterns = [
...
re_path(r'search/', react_views.ReactAppView.as_view()),
]
Run Code Online (Sandbox Code Playgroud)
PROJECT_NAME/views.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,
)
Run Code Online (Sandbox Code Playgroud)
ReactAppView在 React 端index.html创建的函数访问yarn build。基本上,我只将 React 用于搜索视图,除了搜索视图之外,我还使用了 jQuery,因为它首先是用 jQuery 开发的。
自从我发现我需要 Next.js 在 React 中使用服务器端渲染 (SSR) 后,我一直在尝试将 React 应用程序迁移到 Next.js。但是,Next.js 没有index.html. 它只是pages/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/3.1/howto/static-files/
在 Next.js 方面,您需要遵循https://nextjs.org/docs/advanced-features/static-html-export 上的示例,或者手动创建一个index.html包含您正在使用的所有 next.js 包的文件。
| 归档时间: |
|
| 查看次数: |
8236 次 |
| 最近记录: |