在 Vite 开发服务器(多页面应用)中自定义 URL

Custom URL in Vite dev server (multi page app)

我正在使用 Vite(从 Webpack 迁移)构建一个多页面应用程序。

要在开发服务器中打开登录页面,我必须转到:localhost:3010/login.html

是否可以调整 Vite 配置以使用 URL 作为 login.html 服务:localhost:3010/login(没有 .html)?

// vite.config.js excerpt

export default {
  build: {
    rollupOptions: {
      input: {
        index: new URL('./index.html', import.meta.url).pathname,
        login: new URL('./login.html', import.meta.url).pathname,
      }
    }
  },
  server: {
    port: 3010,
    proxy: {
      '/api': 'http://localhost:5000/',
    },
  },
};

使用 Vite 插件的 configureServer(server) API. That method's server argument is a ViteDevServer, whose middlewares property is the underlying Connect instance. Call middlewares.use() 配置 Vite 开发服务器,使用充当自定义中间件的方法。

这是一个基本的插件,配置开发服务器用[=18=替换/login,添加到Vite配置中的plugins array

import { defineConfig } from 'vite'

const LoginHtmlFallbackPlugin = {
  name: 'login-html-fallback',
  configureServer(server) {
    server.middlewares.use('/login', (req, res, next) => {
      req.url += '.html'
      next()
    })
  }
}

export default defineConfig({
  plugins: [
    LoginHtmlFallbackPlugin
  ],
})

demo 1

还有一个更动态的插件,仅在存在时回退到相应的 .html 文件(将 .html 附加到无扩展名的 URL):

// build/plugins/html-ext-fallback.js
import path from 'path'
import fs from 'fs'

export default (options) => ({
  name: 'html-ext-fallback',
  configureServer(server) {
    server.middlewares.use((req, res, next) => {
      // Check extensionless URLs but ignore the `/` root path
      if (req.originalUrl.length > 1 && !path.extname(req.originalUrl)) {
        if (fs.existsSync(path.join(options.rootDir, `${req.originalUrl}.html`))) {
          req.url += '.html'
        }
      }
      next()
    })
  }
})

// vite.config.js
import { defineConfig } from 'vite'
import HtmlExtFallbackPlugin from './build/plugins/html-ext-fallback'

export default defineConfig({
  plugins: [
    HtmlExtFallbackPlugin({ rootDir: __dirname })
  ],
})

demo 2