From 17089cd716755c5f5e28e10153b3fd008114441f Mon Sep 17 00:00:00 2001 From: Mplan Date: Thu, 23 Jul 2026 02:51:45 +0800 Subject: [PATCH] fix(seo): load site URL from Vite environment --- vite.config.ts | 50 +++++++++++++++++++++++++++++--------------------- 1 file changed, 29 insertions(+), 21 deletions(-) diff --git a/vite.config.ts b/vite.config.ts index 87b5fce..a1924f0 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -1,4 +1,4 @@ -import { defineConfig } from 'vite' +import { defineConfig, loadEnv } from 'vite' import { mkdirSync, writeFileSync } from 'node:fs' import { fileURLToPath, URL } from 'node:url' import vue from '@vitejs/plugin-vue' @@ -10,17 +10,20 @@ const publicRoutes = [ '/community', ] -function getSiteUrl() { - const explicitUrl = process.env.VITE_SITE_URL - const siteUrl = explicitUrl - return siteUrl +const DEFAULT_SITE_URL = 'http://localhost:5173' + +function getSiteUrl(value?: string) { + const siteUrl = new URL(value?.trim() || DEFAULT_SITE_URL) + if (!['http:', 'https:'].includes(siteUrl.protocol)) { + throw new Error('VITE_SITE_URL 必须使用 http 或 https 协议') + } + return siteUrl.href.replace(/\/$/, '') } -function seoFilesPlugin() { +function seoFilesPlugin(siteUrl: string) { return { name: 'opencloud-seo-files', closeBundle() { - const siteUrl = getSiteUrl() mkdirSync('dist/.well-known', { recursive: true }) const robots = [ @@ -55,19 +58,24 @@ function seoFilesPlugin() { } } -export default defineConfig({ - plugins: [vue(), tailwindcss(), seoFilesPlugin()], - server: { - port: 5173, - strictPort: true, - }, - preview: { - port: 5173, - strictPort: true, - }, - resolve: { - alias: { - '@': fileURLToPath(new URL('./src', import.meta.url)), +export default defineConfig(({ mode }) => { + const env = loadEnv(mode, process.cwd(), 'VITE_') + const siteUrl = getSiteUrl(env.VITE_SITE_URL) + + return { + plugins: [vue(), tailwindcss(), seoFilesPlugin(siteUrl)], + server: { + port: 5173, + strictPort: true, }, - }, + preview: { + port: 5173, + strictPort: true, + }, + resolve: { + alias: { + '@': fileURLToPath(new URL('./src', import.meta.url)), + }, + }, + } })