Vue 配置子路径

Vite Vue Nginx About 943 words

场景

/admin开始的路径都是Vue单页面应用的管理后台页面。

框架

使用了Vue 3 + Vue Router 4 + Vite 5 + Nginx

配置

Vite

使用base指定子路径字符串。

export default defineConfig({
  base: '/admin',
  server: {
    port: 3000,
    proxy: {
      '/api': {
        target: 'http://localhost:8000/api',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, ''),
     }
    }
  },
})

Vue Router

在路由@router/index.js中也需要指定相同的值。

createWebHistory指定base属性。

import.meta.env.BASE_URLVite提供的内置变量,指向的就是defineConfig中的base

const router = VueRouter.createRouter({
  history: VueRouter.createWebHistory(import.meta.env.BASE_URL),
  routes,
})

export default router

Nginx

location /admin {
    alias /usr/local/html;
    try_files $uri $uri/ /index.html last;
    index  index.html;
}


location /api {
    proxy_pass http://localhost:8080/api; 
}

参考

https://cn.vitejs.dev/config/shared-options#base

https://router.vuejs.org/zh/api/interfaces/RouterHistory.html#Properties-base

Views: 203 · Posted: 2024-02-18

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh