-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvite-plugin-coi.js
More file actions
63 lines (55 loc) · 1.86 KB
/
vite-plugin-coi.js
File metadata and controls
63 lines (55 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
/**
* Vite 插件:自动注入 COI Service Worker
* 用于在 GitHub Pages 等环境中启用 SharedArrayBuffer
*/
export default function vitePluginCOI() {
let config
const coiScriptPath = path.resolve(__dirname, 'public/coi-serviceworker.js')
return {
name: 'vite-plugin-coi',
configResolved(resolvedConfig) {
config = resolvedConfig
},
// 仅在生产构建时注入 Service Worker 脚本(开发环境通过 dev server headers 实现隔离)
transformIndexHtml(html, ctx) {
if (ctx.server) {
// 开发模式:dev server 已直接设置 COOP/COEP headers,无需 SW
return []
}
return [
{
tag: 'script',
attrs: {
src: './coi-serviceworker.js'
},
injectTo: 'head-prepend'
}
]
},
// 开发模式:直接通过 Vite dev server 设置 COOP/COEP headers,无需 Service Worker
configureServer(server) {
server.middlewares.use((req, res, next) => {
res.setHeader('Cross-Origin-Embedder-Policy', 'require-corp')
res.setHeader('Cross-Origin-Opener-Policy', 'same-origin')
next()
})
},
// 生产构建:复制 Service Worker 文件到 dist
closeBundle() {
if (config.command === 'build') {
const outDir = config.build.outDir || 'dist'
const destPath = path.resolve(__dirname, outDir, 'coi-serviceworker.js')
if (fs.existsSync(coiScriptPath)) {
fs.copyFileSync(coiScriptPath, destPath)
console.log('✓ COI Service Worker copied to', destPath)
} else {
console.warn('⚠ COI Service Worker not found at', coiScriptPath)
}
}
}
}
}