使用 vite 构建(vue3)的 fastapi 静态文件

问题描述 投票:0回答:1

我目前正在从 vue2 应用程序(使用 vue cli 服务创建)迁移到 vue3(使用 vite)。 我有一个用 fastapi 编写的后端,它充当后端并提供静态前端文件。

这是我的main.py,当我这样使用它时,它可以与旧应用程序(vue cli)一起正常工作

app.mount("/static", StaticFiles(directory="static"), name="static")


@app.get("/{full_path:path}")
def show_test():
    return FileResponse("static/index.html", media_type="text/html")

我的 vue.config.js 有这个,以使其正常工作:

module.exports = {
  publicPath: "/static/",
};

因此需要 publicPath 才能使用 vue cli 在 vue2 中工作。

但现在我使用 vite 创建了应用程序,不再有“publicPath”,而是 vite.config.js 的“base”属性

export default defineConfig({
...
  base: '/static/',
})

使用此配置如果有效,但现在我在每个路径的 url 中得到“静态”,例如 localhost:8000/static/login,当我刷新页面时,它会导致错误,因为它无法识别该 url。

使用 vue2 应用程序和 publicPath,它工作正常,只显示 localhost:8000/login,刷新也工作正常。

那么需要在 fastapi api.py 或 vite.config.ts 中更改哪些内容才能使其正常工作?

谢谢你

build static vuejs3 fastapi vite
1个回答
0
投票

好吧,我设法使用 npm 插件让它工作: https://www.npmjs.com/package/vite-plugin-dynamic-base

所以这是我的 vite.config.ts:

import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import { dynamicBase } from 'vite-plugin-dynamic-base'

import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    vueJsx(),
    dynamicBase({
      // dynamic public path var string, default window.__dynamic_base__
      publicPath: '',
      // dynamic load resources on index.html, default false. maybe change default true
      transformIndexHtml: false
    })
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  },
  base: '/static/',
})

现在一切正常了。

© www.soinside.com 2019 - 2024. All rights reserved.