Django - 从静态文件夹提供 SPA

Django - serving a SPA from static folder

我们的 django 服务器是我们的 API 以及操作后端。我正在努力通过编写一个慢慢取代现有操作后端的 Vue SPA 来改进我们的操作后端。

我是前端,有点迷失在 Django 配置的复杂性中。有人可以针对这个问题提出一个合理的解决方案吗?

我希望从静态文件夹中提供该应用程序,并已设置:

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
    os.path.join(BASE_DIR, '../console/dist'),
)

这有效,我在查看源代码时可以看到我的代码,但只能在 http://localhost:8000/static/console/index.html

1) 这行不通,因为作为 SPA,Vue 需要控制路由。从 Django 方面,我如何才能 /static/console/* 使用我的 Vue 应用程序? Vue端,Webpack和Vue-router需要配置什么?

2) 尽管我可以看到我编译的应用程序源代码,但我还是收到错误消息:

Creating Application Cache with manifest http://localhost:8000/static/appcache/manifest.appcache
index.html:1 Application Cache Checking event
index.html:1 Application Cache Downloading event
index.html:1 Application Cache Progress event (0 of 7) http://localhost:8000/favicon.ico
index.html:1 Application Cache Error event: Resource fetch failed (4) http://localhost:8000/favicon.ico
index.html:1 Uncaught (in promise) TypeError: Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetching the script.

这很奇怪,因为 http://localhost:8000/favicon.ico 是一个有效的 URL。我感觉这也是一个 Webpack 问题。

我有哪些选择?

我用 Django 为 Angular2 应用程序做了这个(它没有问题)- 我认为它可以帮助你。

urls.py:

# catch-all pattern for compatibility with the Angular routes
url(r'^$', views.index),
url(r'^(?P<path>.*)/$', views.index),

views.py

def index(request, path=''):
    """
    Renders the Angular2 SPA
    """
    return render(request, 'index.html')

index.html

{% load staticfiles %}
...some other stuff...
<app-root>Loading... </app-root>
<script src="{% static 'js/jquery-3.1.1.min.js' %}"></script>
<script src="{% static  'js/materialize.min.js'%}"></script>

<!-- Angular app -->
<script type="text/javascript" src="{% static 'js/app/inline.bundle.js' %}"></script>
<script type="text/javascript" src="{% static 'js/app/vendor.bundle.js' %}"></script>
<script type="text/javascript" src="{% static 'js/app/main.bundle.js' %}"></script>
<script type="text/javascript" src="{% static 'js/app/scripts.bundle.js' %}"></script>¸

settings.py

TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATE_DIR],
        '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',
            ],
        },
    },
]

我的index.html存放在templates目录,我的js应用文件存放在static/js/app.