import fs from 'node:fs'
import path from 'node:path'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// 浏览器会以 CORS 为由拒绝从 file:// 加载外部 module 脚本,
// 因此构建结束后把唯一的 JS/CSS 内联进 index.html,让 dist/index.html 可以直接双击预览。
// 这不会改变接口路径或运行逻辑;通过后端静态托管时同样可用。
function inlineDistPlugin() {
let outDir = ''
return {
name: 'qlinker-inline-dist',
apply: 'build',
configResolved(config) {
outDir = path.resolve(config.root, config.build.outDir)
},
closeBundle() {
const htmlPath = path.join(outDir, 'index.html')
if (!fs.existsSync(htmlPath)) return
let html = fs.readFileSync(htmlPath, 'utf8')
html = html.replace(/`
})
html = html.replace(/]*rel="stylesheet"[^>]*href="\.\/([^"]+\.css)"[^>]*>/g, (match, href) => {
const css = fs.readFileSync(path.join(outDir, href), 'utf8').replace(/<\/style/gi, '<\\/style')
return ``
})
fs.writeFileSync(htmlPath, html, 'utf8')
console.log('[qlinker] JS/CSS 已内联到 dist/index.html,可直接双击打开做静态预览')
}
}
}
// 开发期通过代理访问后端,避免在生产配置里写死后端地址。
export default defineConfig({
plugins: [vue(), inlineDistPlugin()],
// 相对 base:dist 资源使用 ./assets 前缀,可直接双击 dist/index.html 预览。
base: './',
server: {
port: 5173,
proxy: {
'/api': {
target: 'http://127.0.0.1:8080',
changeOrigin: true
}
}
},
// 预览构建产物时同样把 /api 转发到本地后端,便于在 4173 上做真实联调。
preview: {
port: 4173,
proxy: {
'/api': {
target: 'http://127.0.0.1:8080',
changeOrigin: true
}
}
}
})