跳到主要内容

vite:html-inline-script-proxy

2023年12月28日
柏拉文
越努力,越幸运

一、认识


对于 HTML 中的内联脚本,Vite 会通过 vite:html-inline-script-proxy 插件来进行加载。比如下面这个 script 标签:

<script type="module">
import React from 'react';
console.log(React)
</script>

这些内容会在后续的 build-html 插件从 HTML 代码中剔除,并且变成下面的这一行代码插入到项目入口模块的代码中:

import '/User/xxx/vite-app/index.html?http-proxy&index=0.js'

vite:html-inline-script-proxy 就是用来加载这样的模块

二、实现


const htmlProxyRE = /\?html-proxy&index=(\d+)\.js$/

export function htmlInlineScriptProxyPlugin(config: ResolvedConfig): Plugin {
return {
name: 'vite:html-inline-script-proxy',
load(id) {
const proxyMatch = id.match(htmlProxyRE)
if (proxyMatch) {
const index = Number(proxyMatch[1])
const file = cleanUrl(id)
const url = file.replace(normalizePath(config.root), '')
// 内联脚本的内容会被记录在 htmlProxyMap 这个表中
const result = htmlProxyMap.get(config)!.get(url)![index]
if (typeof result === 'string') {
// 加载脚本的具体内容
return result
} else {
throw new Error(`No matching HTML proxy module found from ${id}`)
}
}
}
}
}