# scanImports 函数
export async function scanImports(config: ResolvedConfig): Promise<{
deps: Record<string, string>
missing: Record<string, string>
}
# 参数
config 自义定配置
# 返回值
deps扫描出来需要构建的依赖。missing扫描后的需要构建的缺失依赖。
# 自定义 optimizeDeps.entries 为入口
# 文档解释
默认情况下,Vite 会抓取你的 index.html 来检测需要预构建的依赖项。如果指定了 build.rollupOptions.input,Vite 将转而去抓取这些入口点。
如果这两者都不合你意,则可以使用此选项指定自定义条目——该值需要遵循 fast-glob (opens new window) 模式 ,或者是相对于 Vite 项目根的模式数组。这将覆盖掉默认条目推断。
let entries: string[] = []
声明入口变量 entries。
const explicitEntryPatterns = config.optimizeDeps?.entries
if (explicitEntryPatterns) {
entries = await globEntries(explicitEntryPatterns, config)
}
optimizeDeps.entries 是 Vite 的依赖优化选项的一个 API, 同时也是第一优先级,如果定义了, 则从 optimizeDeps.entries 配置中进行入口解析。
import glob from 'fast-glob'
function globEntries(pattern: string | string[], config: ResolvedConfig) {
return glob(pattern, {
cwd: config.root,
ignore: [
'**/node_modules/**',
`**/${config.build.outDir}/**`,
`**/__tests__/**`
],
absolute: true
})
}
globEntries 是调用了 NPM 模块包 fast-glob 进行寻找入口文件。
cwd是寻找到的起始目录。ignore忽略的文件, 内置过滤以下内容。
node_modules文件夹。- 打包后的文件夹。
__tests__单元测试文件。
absolute最后解析完返回绝对路径。
# 自定义 build.rollupOptions.input 为入口点
const buildInput = config.build.rollupOptions?.input
if (XXX) {
...
} else if (buildInput) {
const resolvePath = (p: string) => path.resolve(config.root, p)
if (typeof buildInput === 'string') {
entries = [resolvePath(buildInput)]
} else if (Array.isArray(buildInput)) {
entries = buildInput.map(resolvePath)
} else if (isObject(buildInput)) {
entries = Object.values(buildInput).map(resolvePath)
} else {
throw new Error('invalid rollupOptions.input value.')
}
}
没有配置 optimizeDeps.entries, 接下来以 build.rollupOptions.input 为入口点进行扫描。
rollupOptions 是与 rollup 文档保持一致。会存在三种配置方案。
- 字符串
'./index.html'
- 数组
['./index.html', './index2.html']
- 对象的方式
{
"index": "./index.html",
"index2": "./index2.html"
}
# 寻找方式
通过 resolvePath 方法解析路径, 基于config.root相对的路径与入传路径合并成绝对路径写入 entries 变量中。
如果格式不是以上三种数据类型,将提示检查 rollupOptions.input 值。
小技巧
通过 rollupOptions.input 寻找入口, 不存在被过滤问题, 如果不想被过滤进行约束, 可以通过 rollupOptions.input 寻找入口,在有些启动是基于node_modules 模块中的工程, 利用 build.rollupOptions.input 写入扫描入口, 将可以防止文件被过滤。
# 默认入口
else {
entries = await globEntries('**/*.html', config)
}
以上没有配置任何自定义入口时,将会抓取以 root 为根目录的.html文件为扫描入口。
# 检查确定后的入口文件
const JS_TYPES_RE = /\.(?:j|t)sx?$|\.mjs$/
const htmlTypesRE = /\.(html|vue|svelte)$/
// Non-supported entry file types and virtual files should not be scanned for
// dependencies.
entries = entries.filter(
(entry) =>
(JS_TYPES_RE.test(entry) || htmlTypesRE.test(entry)) &&
fs.existsSync(entry)
)
在描入口之前, 需要对扫描的入口检查可扫描性, 需要以下两点, 否则将不合法的入口地址进行过滤。
- 允许扫描文件类型
.js.tsx.jsx.mjs.html.vue.svelte
- 文件存在
if (!entries.length) {
return { deps: {}, missing: {} }
}
如果没有确定任何扫描入口, 即 entries 没有数组长度, deps 依赖和 missing 依赖缺失都以空对象返回。