34 lines
1.0 KiB
JavaScript
34 lines
1.0 KiB
JavaScript
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 = /<script[^>]*>[\s\S]*?<\/script>/g
|
|
const headScripts = []
|
|
|
|
// 移除 head 中的脚本标签并保存它们
|
|
html = html.replace(/<head>([\s\S]*?)<\/head>/, (match, headContent) => {
|
|
const newHeadContent = headContent.replace(scriptRegex, (script) => {
|
|
if (script.includes('type="module"')) {
|
|
headScripts.push(script)
|
|
return ''
|
|
}
|
|
return script
|
|
})
|
|
return `<head>${newHeadContent}</head>`
|
|
})
|
|
|
|
// 将脚本标签添加到 body 末尾
|
|
html = html.replace('</body>', `${headScripts.join('')}\n</body>`)
|
|
|
|
return html
|
|
}
|
|
}
|
|
}
|
|
}
|