vite.config.js
vite.config.js 增加?base: './'
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'// https://vitejs.dev/config/
export default defineConfig({base: './',resolve: {alias: {'@': fileURLToPath(new URL('./src', import.meta.url))}},plugins: [vue()]
})
打包后 index.html
項目運行位置
項目是放在根目錄運行,使用默認配置?import.meta.env.BASE_URL 默認輸出 '/' ;
?router.js
import { createRouter, createWebHistory } from 'vue-router'import HomeView from '../views/HomeView.vue'const routes = [{path: '/',name: 'home',component: HomeView},{path: '/about',name: 'about',component: () => import('../views/AboutView.vue')}
]const router = createRouter({history: createWebHistory(import.meta.env.BASE_URL),routes
})export default router
如果項目打包后放在二級目錄運行;
例如:
項目放在:F:/test/dist
項目訪問地址是:http://127.0.0.1/my_project
?router.js?
import { createRouter, createWebHistory } from 'vue-router'import HomeView from '../views/HomeView.vue'const routes = [{path: '/',name: 'home',component: HomeView},{path: '/about',name: 'about',component: () => import('../views/AboutView.vue')}
]const router = createRouter({// history: createWebHistory(import.meta.env.BASE_URL), // 這是默認的配置history: createWebHistory('/test'), // 打包后dist放在了 test 目錄下routes
})export default router
nginx配置
nginx.conf?
server {listen 80;server_name localhost;location /my_project {alias F:/test/dist;index index.html index.htm;if (!-e $request_filename) {rewrite ^/(.*) /my_project /index.html last;break;}}}
可參考:vue使用記錄_刷新頁面加載會觸發哪幾個鉤子-CSDN博客?里面的【路由History模式打包頁面空白】