export default function scriptInjectPlugin() { return { name: 'vite-plugin-script-inject', enforce: 'post', transformIndexHtml: { enforce: 'post', transform(html, ctx) { // 只在生产构建时处理 if (!ctx.bundle) return html // 提取 head 中的所有脚本标签 const scriptRegex = /]*>[\s\S]*?<\/script>/g const headScripts = [] // 移除 head 中的脚本标签并保存它们 html = html.replace(/([\s\S]*?)<\/head>/, (match, headContent) => { const newHeadContent = headContent.replace(scriptRegex, (script) => { if (script.includes('type="module"')) { headScripts.push(script) return '' } return script }) return `${newHeadContent}` }) // 将脚本标签添加到 body 末尾 html = html.replace('', `${headScripts.join('')}\n`) return html } } } }