首页 > 解决方案 > Django+Vue+webpack 配置

问题描述

我正在尝试设置一个项目,但不知何故我无法正确地将我的后端连接到我的前端

dev.py

from .settings import *

DEBUG = True
ALLOWED_HOSTS = ["*"]
MIDDLEWARE.append("debug_toolbar.middleware.DebugToolbarMiddleware")
INSTALLED_APPS.append("debug_toolbar")
INTERNAL_IPS = ("127.0.0.1", "localhost")

WEBPACK_LOADER = {
    "DEFAULT": {
        "BUNDLE_DIR_NAME": "",
        "STATS_FILE": os.path.join(BASE_DIR, "frontend/webpack-stats.json"),
        # 'STATS_FILE': BASE_DIR.joinpath('frontend', 'webpack-stats.json'),
    }
}

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]
MEDIA_URL = "/dmedia/"
MEDIA_ROOT = os.path.join(BASE_DIR, "mediafiles")

STATIC_URL = "/static/"
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")

VUE_ROOT = os.path.join(BASE_DIR, "frontend\\static\\")

剪裁自settings.py

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(
    os.path.dirname(os.path.abspath(__file__))))
STATICFILES_ROOT = os.path.join(BASE_DIR, "staticfiles")



# Application definition

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "ObjectMgr",
    "webpack_loader",
]

ROOT_URLCONF = "ObjectMgr.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [
            os.path.join(BASE_DIR, "templates"),
        ],
        "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",
            ],
        },
    },
]

WSGI_APPLICATION = "ObjectMgr.wsgi.application"


# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.sqlite3",
        "NAME": os.path.join(BASE_DIR, "db.sqlite3"),
    }
}

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/

STATIC_URL = "/static/"

index.html

{% load render_bundle from webpack_loader %}
{% load static from staticfiles %}

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>frontend</title>
  <meta http-equiv=X-UA-Compatible content="IE=edge">
  <meta name=viewport content="width=device-width,initial-scale=1">
  <link rel=icon href="{% static 'favicon.ico' %}"> {% render_bundle 'chunk-vendors' %}
</head>

<body><noscript><strong>We're
      sorry but frontend doesn't work properly without JavaScript enabled. Please enable it to
      continue.</strong></noscript>

  {% for i in 'abc' %}
  <strong>{{ i }} DJANGO PART</strong>
  {% endfor %}

  <div id=app>
  </div>
    {% render_bundle 'app' %}

</body>

</html>

wsgi.py

"""
WSGI config for ObjectMgr project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ObjectMgr.settings")

application = get_wsgi_application()

urls.py

import os

from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.urls import path
from django.views.generic import TemplateView
from django.views.generic.base import RedirectView
from django.views.static import serve

favicon_view = RedirectView.as_view(url=os.path.join(settings.STATIC_URL, "favicon.ico"), permanent=True)

urlpatterns = [
    path("favicon.ico", favicon_view),
    path("", TemplateView.as_view(template_name="index.html")),
    path("admin/", admin.site.urls),
    url(r"^static/(?P<path>.*)$", serve,
        {"document_root": settings.STATIC_ROOT}),
    url(r"^dmedia/(?P<path>.*)$", serve,
        {"document_root": settings.MEDIA_ROOT}),

    url(r"^media/(?P<path>.*)$", serve,
        {"document_root": os.path.join(settings.VUE_ROOT, "media")}),
    url(r"^img/(?P<path>.*)$", serve,
        {"document_root": os.path.join(settings.VUE_ROOT, "img")}),
    url(r"^js/(?P<path>.*)$", serve,
        {"document_root": os.path.join(settings.VUE_ROOT, "js")}),
    url(r"^css/(?P<path>.*)$", serve,
        {"document_root": os.path.join(settings.VUE_ROOT, "css")}),
    url(r"^fonts/(?P<path>.*)$", serve,
        {"document_root": os.path.join(settings.VUE_ROOT, "fonts")}),
]

if settings.DEBUG:
    import debug_toolbar
    urlpatterns = [
        url(r"^__debug__/", include(debug_toolbar.urls)),
    ] + urlpatterns

vue.config.js

var BundleTracker = require('webpack-bundle-tracker')
var WriteFilePlugin = require('write-file-webpack-plugin')


module.exports = {
  outputDir: (process.env.NODE_ENV === "production" ? 'dist' : 'static'),
  publicPath: '/',

 devServer: {
    publicPath: "http://localhost:8080/",
    headers: {
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
      "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept, Accept-Encoding, Accept-Language, Access-Control-Request-Headers, Access-Control-Request-Method",
      "Access-Control-Allow-Credentials": "true",
    },
  },

  chainWebpack: config => {
    config.optimization.splitChunks({
      cacheGroups: {
        vendors: {
          name: 'chunk-vendors',
          test: /[\\\/]node_modules[\\\\/]/,
          priority: -10,
          chunks: 'initial'
        },
        common: {
          name: 'chunk-common',
          minChunks: 2,
          priority: -20,
          chunks: 'initial',
          reuseExistingChunk: true
        }
      }
    })
  },
  configureWebpack: {
    output: {
      filename: 'js/[name].js',
      chunkFilename: 'js/[name].js'
    },
    plugins: [
      new WriteFilePlugin(),
      (process.env.NODE_ENV === "production" ?
        new BundleTracker({
          filename: 'webpack-stats-prod.json',
          publicPath: '/'
        }) :
        new BundleTracker({
          filename: 'webpack-stats.json',
          publicPath: 'http://localhost:8080/'
        })
      )
    ]
  }
}

first problem in index.html

'staticfiles' is not a registered tag library. Must be one of:
admin_list
admin_modify
admin_urls
cache
i18n
l10n
log
static
tz
webpack_loader

如果我将 import from 更改为{% load static from staticfiles %}{% load static from static %}我会收到另一个与 webpack 配置相关的错误,我无法修复

In template /ObjectMgr/templates/index.html, error at line 12

WebpackBundleLookupError at /

Cannot resolve bundle chunk-vendors.

对此的任何帮助将不胜感激!

标签: djangovue.jswebpackwebpack-dev-servervue-cli

解决方案


推荐阅读