前端(以Vue爲例)webpack打包後dist文件包如何部署到django後臺中

     因爲如今前端使用的三大框架配合webpack能夠實現快速打包,爲部署到服務端提供了很是大的便利,那麼在前端打包後,應該作些什麼能夠部署到django的後臺中呢?html

1.打包後文件包dist前端


進入到 dist文件包會發現是這個樣子的:vue

 

2.在django項目中建立前端文件包(靜態資源包,我習慣起名爲frontend) 
       而後把dist文件包中的static文件包和index.html拷貝過去,接着把static文件包中的全部文件和index文件都剪切到上一層目錄(都在frontend中),因爲咱們Vue構建的是單頁應用因此通常只有一個html。作完這些後吧static這個空文件包刪掉就好了。這樣就造成了django後臺的靜態文件包。webpack

 

3.在settings中配置靜態文件以及模板
          這裏的index.html就至關因而template中的html文件,爲了方便就把靜態資源和這個模板文件整合在一個文件包中。web

          首先是template配置:django

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'frontend')],
'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',
],
},
},
]
       而後是靜態文件配置: api

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "frontend"),
]
4.建立一個app,而且在views中寫一個index路由函數,而且在url中配置首頁
#加載靜態界面index首頁
def index(request):
request.META["CSRF_COOKIE_USED"] = True
return render(request,'index.html')
request.META["CSRF_COOKIE_USED"] = True這句能夠對vue單頁應用進行csrf_token設置,方便進行csrf防護app

urlpatterns = [
url(r'^baseapi/', include("baseapp.urls")),
url(r'^.*?$',views.index,name="index"),
]
 url(r'^.*?$',views.index,name="index")設置後,啓動django,訪問8000端口就能夠加載到前端的路由了框架

或者,直接在url中加入:frontend

from django.views.generic import TemplateView
path('', TemplateView.as_view(template_name='index.html'), name='index'),

--------------------- 原文:https://blog.csdn.net/qq_41000891/article/details/82961680

相關文章
相關標籤/搜索