Django - 从静态文件夹提供SPA

Zak*_*Zak 3 django webpack vue.js vue-router

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

我在Django配置的错综复杂的前端和一点点迷失.有人可以为这个问题建议一个理智的解决方案吗?

我想让应用程序从静态文件夹中提供,并设置:

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
    os.path.join(BASE_DIR, '../console/dist'),
)
Run Code Online (Sandbox Code Playgroud)

这有效,我可以在查看源代码时看到我的代码,但只能在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.
Run Code Online (Sandbox Code Playgroud)

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

我有什么选择?

Jan*_*lli 6

我为Django的Angular2应用程序做了这样的事情(它没有问题) - 我认为它可以帮到你.

urls.py:

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

views.py

def index(request, path=''):
    """
    Renders the Angular2 SPA
    """
    return render(request, 'index.html')
Run Code Online (Sandbox Code Playgroud)

的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>¸
Run Code Online (Sandbox Code Playgroud)

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',
            ],
        },
    },
]
Run Code Online (Sandbox Code Playgroud)

我的index.html存储在templates目录中,我的js app文件存储在static/js/app中.