Vue3+vite打包后页面空白问题

时间:2024-03-02 22:31:25

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模式打包页面空白】