在我的项目中我使用Vue 3.2.36 + Vite 2.9.9 + VueRouter 4.1.3
我使用
npm run dev
运行开发服务器。routes: [
{
path: '/',
component: Home,
},
{
path: '/about',
component: () => import('@/views/About.vue'),
},
{
path: '/user-details/:login',
name: 'userDetails',
component: () => import('@/views/User.vue'),
},
{
path: '/:pathMatch(.*)*',
component: NotFound,
}
],
当我使用
router.push({name: 'userDetails', params: {login: 'john.smith'}})
以编程方式导航时,userDetails
页面/组件正确显示。NotFound
组件不会显示。
工作示例:此处
我已将问题隔离给Vite。使用 Vue CLI 一切正常。
我的
vite.config.js
:
import loadVersion from 'vite-plugin-package-version';
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
export default defineConfig(() => {
return {
server: {
port: 8080,
},
plugins: [vue(), loadVersion()],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url)),
},
},
envDir: './src/configuration',
css: {
preprocessorOptions: {
scss: {
additionalData: '@import "@/assets/scss/_variables.scss";',
},
},
},
};
});
检查了我的
index.html
:<script type="module" src="/src/main.js"></script>
vue-router
历史模式文档,在 caveat 部分中,它表示如果未找到路由,路由器应默认为 index.html
,并且它使用 Vue CLI 执行此操作,但不使用 Vite。
问题: 我使用 vite + 路由器 + 历史记录模式,并在我的开发环境中遇到这个问题,当我第一次启动 vite 应用程序时,路由器将启动“/”并将我的路由器路径加载到“/m/xxx”中,当我重新加载时或者在此页面'/m/xxx'刷新应用程序,vite将使用'/m/xxx'作为根基本路径而不是'/'
生产中: 我们可以使用
nginx
重定向路径来解决历史模式,就像旧的常规方法一样。
但是我们如何解决开发模式下的问题,在webpack中有一个参数
historyApiFallback
来重写后备,
但我没有在 vite 中找到配置它,所以我找到了一种方法,将 <base href='/' />
放在我的 dev index.html 中来设置根路径,这样当我重新加载页面时,它将使用 '/'作为基本根而不是获取'/m/xxx/src/index.ts'。
import { createHtmlPlugin } from 'vite-plugin-html';
defineConfig({
plugins:[createHtmlPlugin({
minify: true,
entry: 'src/index.ts',
template: 'build/vite/index.vite.html',
inject: isProduction ? {} : {
tags: [
{
injectTo: 'head-prepend',
tag: 'base',
attrs: {
href: '/'
}
}
]
}
})
]
})
另一种方法,尝试将
vite-plugin-html
替换为vite-plugin-parse-html
可能会更好地解决这个问题
我的 Web 应用程序位于 Azure DevOps 上,但位于 Linux 上 对于 Linux Web 应用程序,您必须添加下一个命令才能在启动时运行 Web 应用程序命令。这对我有用。
pm2 serve /home/site/wwwroot --no-daemon --spa
您可以在本文中查看更多内容Azure webapp linux 上的 React 应用程序
您可以尝试使用 dist 文件夹中的 .htaccess 文件
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>
[https://router.vuejs.org/guide/essentials/history-mode.html#example-server-configurations][1]
如[https://gist.github.com/Prezens/f99fd28124b5557eb16816229391afee][2]
中发现