在 Django 中使用 Vue:如何将 publicPath 与静态文件前缀分开

Using Vue with Django: How to separate publicPath from static file prefix

我正在尝试将我现有的庞大的 Django 项目(目前在前端的各个页面中使用来自 CDN 的 Vue)转换为通过 NPM 的 SPA,后端和前端现在是分开的(除了 Django 处理一些URL 路由并最初加载 Vue。

我 运行 遇到静态文件和 URL 路由问题。在vue.config.js中,原本建议我设置值如下:

const pages = {
  index: "src/main.js"
};
module.exports = {
  runtimeCompiler: true,
  publicPath: "/static/vue/",
  outputDir: "./dist/static/vue/",
  indexPath: "../../templates/vue_index.html",
  pages: pages
};

这样当结合 Django 查找静态文件的方式时:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'frontend/dist/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',
            ],
        },
    },
]
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'frontend/dist/static')]
STATIC_URL = '/static/'

页面将能够加载。

不幸的是,如果我尝试加载页面,而不是在网站根目录 / 加载,它会在 /static/vue/ 加载(即 localhost:8000/static/vue/)。如果我尝试直接访问 localhost:8000,它会立即重定向到 localhost:8000/static/vue/,我想这是 vue -路由器在做什么。

Django 能够很好地找到 Vue 入口点模板,但它似乎需要 publicPath: "/static/vue/" 以便使用 Django 所需的 [=16] 正确地为 .js 和 .css 文件添加前缀=] 静态 URLs 的前缀(即使我可以将 /static/ 更改为在 / 提供的所有静态文件,我更喜欢开箱即用的 /static/ 前缀).

如果我将 publicPath: "/static/vue/" 更改为 publicPath: "/"publicPath: "./",模板文件仍可正确提供,但我现在丢失了我需要的 /static/vue/ 前缀对于 .js 和 .css 文件,所以它们是 404.

我如何才能告诉 Vue(或更具体地说是 vue-cli)在 / 处提供我的应用程序的根页面,但在初始模板中引用的所有静态文件前加上 /static//static/vue/?

终于找到答案了。对于 Vue 3,在 vue-router 中设置 base URL:

const router = createRouter({
  history: createWebHistory("/"),
  routes
});