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;

        # 外网访问时,加载不了js资源文件配置
        location ^~ /my_project/assets/ {
			alias F:/test/dist/assets/;
			#add_header Content-Type 'text/html; charset=utf-8';
			#return 200 '恭喜你、请求成功';
		}
        
		
		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模式打包页面空白】

GitHub 加速计划 / vu / vue
108
18
下载
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
最近提交(Master分支:2 个月前 )
9e887079 [skip ci] 1 年前
73486cb5 * chore: fix link broken Signed-off-by: snoppy <michaleli@foxmail.com> * Update packages/template-compiler/README.md [skip ci] --------- Signed-off-by: snoppy <michaleli@foxmail.com> Co-authored-by: Eduardo San Martin Morote <posva@users.noreply.github.com> 1 年前
Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐