vue3 vite使用History路由模式打包部署项目注意事项

6,527次阅读
没有评论

共计 1638 个字符,预计需要花费 5 分钟才能阅读完成。

一、Vue Router 的两种路由模式
 

哈希模式(Hash Mode)

        默认模式,URL 结构包含哈希符号 #,例如:http://example.com/#/home。利用 window.location.hash 来跟踪路由变化,浏览器会自动处理哈希的变化而不触发页面重载。
因为哈希值只影响浏览器的历史记录而不发送到服务器,所以无需后端配合即可实现前端路由。
SEO 性能较差,因为搜索引擎通常不会抓取哈希值后面的路径内容。

历史模式(History Mode)

        利用了 HTML5 的 History API,如 window.history.pushState() 和 window.onpopstate 事件。
在此模式下,URL 不包含哈希,呈现常规的路径结构,例如:http://example.com/home。
为了实现前进、后退按钮的正常工作以及防止直接访问某个路由导致 404 错误,需要在服务器端进行适当的配置,将所有的请求都指向应用程序的入口文件,以便 Vue Router 能够接管并解析正确的路由。
历史模式提高了用户体验,URL 易于阅读,也更利于 SEO。

二、History 路由 模式打包部署项目

        在 Vue 3. 中使用 Vue Router 的 history 模式进行项目打包部署时,需要确保打包配置和服务器正确配置来处理路由。否则部署到 Nginx 会出现访问 404、空白等。在项目打包配置及 Nginx 配置有些要注意的地方。以项目名 demo 为例。

1、配置 Vue Router 为 history 模式,在 src/router/index.js 中配置
import {createRouter, createWebHistory} from 'vue-router'
 

const router = createRouter({history: createWebHistory(import.meta.env.BASE_URL),
  routes:[// 定义路由]
})
 
export default router

备注:createWebHistory:history 模式,createWebHashHistory:hash 模式

2、配置 vite.config.js
import {
	fileURLToPath,
	URL
} from 'node:url'

import {defineConfig} from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig(() => {
	return {
		plugins: [vue()
		],
		// 静态站点根路径配置;base:'/demo/';demo 是项目名,解决 Nginx 部署时,访问缺少项目前缀的问题
		base: process.env.NODE_ENV === 'production' ? '/demo/' : '/',// vue-router 中配置,组件匹配
		// publicPath: process.env.NODE_ENV === 'production' ? '/demo/' : '/',// vue.config.js 文件中配置,打包后外部资源的获取
		build: {
			// 设置打包文件夹的名称
			outDir: 'demo'
		},
		resolve: {
			alias: {'@': fileURLToPath(new URL('./src', import.meta.url))
			}
		},
	};
});
3、配置 Nginx,在 conf/nginx.conf 中配置
location /demo/ {
    alias  /path/html/demo/;
    index  index.html index.htm;
    try_files $uri $uri/ /demo/index.html;
}

备注:alias  /path/html/demo/; 中的 path 换成 Nginx 对应的部署路径

原文地址: vue3 vite 使用 History 路由模式打包部署项目注意事项

    正文完
     0
    Yojack
    版权声明:本篇文章由 Yojack 于2024-11-04发表,共计1638字。
    转载说明:
    1 本网站名称:优杰开发笔记
    2 本站永久网址:https://yojack.cn
    3 本网站的文章部分内容可能来源于网络,仅供大家学习与参考,如有侵权,请联系站长进行删除处理。
    4 本站一切资源不代表本站立场,并不代表本站赞同其观点和对其真实性负责。
    5 本站所有内容均可转载及分享, 但请注明出处
    6 我们始终尊重原创作者的版权,所有文章在发布时,均尽可能注明出处与作者。
    7 站长邮箱:laylwenl@gmail.com
    评论(没有评论)