Vite 2.6.11 不支持禁用历史 API 回退,尽管有一个开放的拉取请求引入了可用于禁用历史回退中间件 (vitejs/vite#4640) 的配置。
作为一种解决方法,您可以添加一个custom plugin,它可以有效地禁用历史 API 回退。 Vite 的插件 API 包括 configureServer() hook,它允许将自定义中间件添加到底层 connect 实例。您可以添加一个中间件,为未找到的 URL 请求发送 404 状态代码。
这是编写该插件的一种方法:
// vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
function disableHistoryFallback() {
const path = require('path')
const fs = require('fs')
const ALLOWLIST = [
// internal requests
/^\/__vite_ping/,
/^\/@vite\/client/,
/^\/@id/,
/^\/__open-in-editor/,
// no check needed
/^\/$/,
/^\/index.html/,
]
return {
name: 'disable-history-fallback',
configureServer(server) {
server.middlewares.use((req, res, next) => {
// remove query params from url (e.g., cache busts)
const url = req.url.split('?')[0]
if (ALLOWLIST.some(pattern => pattern.test(url))) {
return next()
}
if (!fs.existsSync(path.join(__dirname, url))) {
console.warn('URL not found:', url)
res.statusCode = 404
res.end()
} else {
next()
}
})
}
}
}
export default defineConfig({
plugins: [vue(), disableHistoryFallback()],
})