我们知道,vite 构建环境分为开发环境和生产环境,不同环境会有不同的构建策略,但不管是哪种环境,vite 都会首先解析用户配置。那接下来,我就与你分析配置解析过程中 vite 到底做了什么?即vite是如何加载配置文件的。
流程梳理
我们先来梳理整体的流程,vite 中的配置解析由 resolveconfig 函数来实现,你可以对照源码一起学习。
加载配置文件
进行一些必要的变量声明后,我们进入到解析配置逻辑中,配置文件的源码如下:
// 这里的 config 是命令行指定的配置,如 vite --configfile=xxx
let { configfile } = config
if (configfile !== false) {
// 默认都会走到下面加载配置文件的逻辑,除非你手动指定 configfile 为 false
const loadresult = await loadconfigfromfile(
configenv,
configfile,
config.root,
config.loglevel
)
if (loadresult) {
// 解析配置文件的内容后,和命令行配置合并
config = mergeconfig(loadresult.config, config)
configfile = loadresult.path
configfiledependencies = loadresult.dependencies
}
}
第一步是解析配置文件的内容,然后与命令行配置合并。值得注意的是,后面有一个记录 configfiledependencies 的操作。因为配置文件代码可能会有第三方库的依赖,所以当第三方库依赖的代码更改时,vite 可以通过 hmr 处理逻辑中记录的 configfiledependencies 检测到更改,再重启 devserver ,来保证当前生效的配置永远是最新的。
解析用户插件
第二个重点环节是 解析用户插件。首先,我们通过 apply 参数 过滤出需要生效的用户插件。为什么这么做呢?因为有些插件只在开发阶段生效,或者说只在生产环境生效,我们可以通过 apply: 'serve' 或 'build' 来指定它们,同时也可以将 apply 配置为一个函数,来自定义插件生效的条件。解析代码如下:
// resolve plugins
const rawuserplugins = (config.plugins || []).flat().filter((p) => {
if (!p) {
return false
} else if (!p.apply) {
return true
} else if (typeof p.apply === 'function') {
// apply 为一个函数的情况
return p.apply({ ...config, mode }, configenv)
} else {
return p.apply === command
}
}) as plugin[]
// 对用户插件进行排序
const [preplugins, normalplugins, postplugins] =
sortuserplugins(rawuserplugins)
接着,vite 会拿到这些过滤且排序完成的插件,依次调用插件 config 钩子,进行配置合并。
// run config hooks
const userplugins = [...preplugins, ...normalplugins, ...postplugins]
for (const p of userplugins) {
if (p.config) {
const res = await p.config(config, configenv)
if (res) {
// mergeconfig 为具体的配置合并函数,大家有兴趣可以阅读一下实现
config = mergeconfig(config, res)
}
}
}
然后,解析项目的根目录即 root 参数,默认取 process.cwd()的结果。
// resolve root const resolvedroot = normalizepath( config.root ? path.resolve(config.root) : process.cwd() )
紧接着处理 alias ,这里需要加上一些内置的 alias 规则,如 @vite/env、@vite/client 这种直接重定向到 vite 内部的模块。
// resolve alias with internal client alias
const resolvedalias = mergealias(
clientalias,
config.resolve?.alias || config.alias || []
)
const resolveoptions: resolvedconfig['resolve'] = {
dedupe: config.dedupe,
...config.resolve,
alias: resolvedalias
}
加载环境变量
加载环境变量的实现代码如下:
// load .env files const envdir = config.envdir ? normalizepath(path.resolve(resolvedroot, config.envdir)) : resolvedroot const userenv = inlineconfig.envfile !== false && loadenv(mode, envdir, resolveenvprefix(config))
loadenv 其实就是扫描 process.env 与 .env文件,解析出 env 对象,值得注意的是,这个对象的属性最终会被挂载到 import.meta.env 这个全局对象上。解析 env 对象的实现思路如下:
遍历 process.env 的属性,拿到指定前缀开头的属性(默认指定为vite_),并挂载 env 对象上
遍历 .env 文件,解析文件,然后往 env 对象挂载那些以指定前缀开头的属性。遍历的文件先后顺序如下(下面的 mode 开发阶段为 development,生产环境为production)
特殊情况下,如果中途遇到 node_env 属性,则挂到 process.env.vite_user_node_env,vite 会优先通过这个属性来决定是否走生产环境的构建。
接下来,是对资源公共路径即 base url 的处理,逻辑集中在 resolvebaseurl 函数当中:
// 解析 base url const base_url = resolvebaseurl(config.base, command === 'build', logger) // 解析生产环境构建配置 const resolvedbuildoptions = resolvebuildoptions(config.build)
resolvebaseurl 里面有这些处理规则需要注意:
空字符或者 ./ 在开发阶段特殊处理,全部重写为 /
.开头的路径,自动重写为 /
以 http(s):// 开头的路径,在开发环境下重写为对应的 pathname
确保路径开头和结尾都是 /
当然,还有对 cachedir 的解析,这个路径相对于在 vite 预编译时写入依赖产物的路径:
// resolve cache directory const pkgpath = lookupfile(resolvedroot, [`package.json`], true /* pathonly */) // 默认为 node_module/.vite const cachedir = config.cachedir ? path.resolve(resolvedroot, config.cachedir) : pkgpath && path.join(path.dirname(pkgpath), `node_modules/.vite`)
紧接着处理用户配置的 assetsinclude,将其转换为一个过滤器函数:
const assetsfilter = config.assetsinclude ? createfilter(config.assetsinclude) : () => false
然后,vite 后面会将用户传入的 assetsinclude 和内置的规则合并:
assetsinclude(file: string) {
return default_assets_re.test(file) || assetsfilter(file)
}
这个配置决定是否让 vite 将对应的后缀名视为静态资源文件(asset)来处理。
路径解析器
这里所说的路径解析器,是指调用插件容器进行路径解析的函数,代码结构如下所示:
const createresolver: resolvedconfig['createresolver'] = (options) => {
let aliascontainer: plugincontainer | undefined
let resolvercontainer: plugincontainer | undefined
// 返回的函数可以理解为一个解析器
return async (id, importer, aliasonly, ssr) => {
let container: plugincontainer
if (aliasonly) {
container =
aliascontainer ||
// 新建 aliascontainer
} else {
container =
resolvercontainer ||
// 新建 resolvecontainer
}
return (await container.resolveid(id, importer, undefined, ssr))?.id
}
}
并且,这个解析器未来会在依赖预构建的时候用上,具体用法如下:
const resolve = config.createresolver()
// 调用以拿到 react 路径
rseolve('react', undefined, undefined, false)
这里有 aliascontainer 和 resolvercontainer 两个工具对象,它们都含有 resolveid 这个专门解析路径的方法,可以被 vite 调用来获取解析结果,本质都是 plugincontainer。
接着,会顺便处理一个 public 目录,也就是 vite 作为静态资源服务的目录:
const { publicdir } = config
const resolvedpublicdir =
publicdir !== false && publicdir !== ''
? path.resolve(
resolvedroot,
typeof publicdir === 'string' ? publicdir : 'public'
)
: ''
至此,配置已经基本上解析完成,最后通过 resolved 对象来整理一下:
const resolved: resolvedconfig = {
...config,
configfile: configfile ? normalizepath(configfile) : undefined,
configfiledependencies,
inlineconfig,
root: resolvedroot,
base: base_url
... //其他配置
}
生成插件流水线
生成插件流水线的代码如下:
;(resolved.plugins as plugin[]) = await resolveplugins( resolved, preplugins, normalplugins, postplugins ) // call configresolved hooks await promise.all(userplugins.map((p) => p.configresolved?.(resolved)))
先生成完整插件列表传给 resolve.plugins,而后调用每个插件的 configresolved 钩子函数。其中 resolveplugins 内部细节比较多,插件数量比较庞大,我们暂时不去深究具体实现,编译流水线这一小节再来详细介绍。
至此,所有核心配置都生成完毕。不过,后面 vite 还会处理一些边界情况,在用户配置不合理的时候,给用户对应的提示。比如:用户直接使用 alias 时,vite 会提示使用 resolve.alias。
最后,resolveconfig 函数会返回 resolved 对象,也就是最后的配置集合,那么配置解析服务到底也就结束了。
加载配置文件详解
首先,我们来看一下加载配置文件 (loadconfigfromfile) 的实现:
const loadresult = await loadconfigfromfile(/*省略传参*/)
这里的逻辑稍微有点复杂,很难梳理清楚,所以我们不妨借助刚才梳理的配置解析流程,深入 loadconfigfromfile 的细节中,研究下 vite 对于配置文件加载的实现思路。
接下来,我们来分析下需要处理的配置文件类型,根据文件后缀和模块格式可以分为下面这几类:
ts + esm 格式
ts + commonjs 格式
js + esm 格式
js + commonjs 格式
识别配置文件的类别
首先,vite 会检查项目的 package.json 文件,如果有 type: "module" 则打上 isesm 的标识:
try {
const pkg = lookupfile(configroot, ['package.json'])
if (pkg && json.parse(pkg).type === 'module') {
ismjs = true
}
} catch (e) {
}
然后,vite 会寻找配置文件路径,代码简化后如下:
let ists = false
let isesm = false
let dependencies: string[] = []
// 如果命令行有指定配置文件路径
if (configfile) {
resolvedpath = path.resolve(configfile)
// 根据后缀判断是否为 ts 或者 esm,打上 flag
ists = configfile.endswith('.ts')
if (configfile.endswith('.mjs')) {
isesm = true
}
} else {
// 从项目根目录寻找配置文件路径,寻找顺序:
// - vite.config.js
// - vite.config.mjs
// - vite.config.ts
// - vite.config.cjs
const jsconfigfile = path.resolve(configroot, 'vite.config.js')
if (fs.existssync(jsconfigfile)) {
resolvedpath = jsconfigfile
}
if (!resolvedpath) {
const mjsconfigfile = path.resolve(configroot, 'vite.config.mjs')
if (fs.existssync(mjsconfigfile)) {
resolvedpath = mjsconfigfile
isesm = true
}
}
if (!resolvedpath) {
const tsconfigfile = path.resolve(configroot, 'vite.config.ts')
if (fs.existssync(tsconfigfile)) {
resolvedpath = tsconfigfile
ists = true
}
}
if (!resolvedpath) {
const cjsconfigfile = path.resolve(configroot, 'vite.config.cjs')
if (fs.existssync(cjsconfigfile)) {
resolvedpath = cjsconfigfile
isesm = false
}
}
}
在寻找路径的同时, vite 也会给当前配置文件打上 isesm 和 ists 的标识,方便后续的解析。
根据类别解析配置
esm 格式
对于 esm 格式配置的处理代码如下:
let userconfig: userconfigexport | undefined
if (isesm) {
const fileurl = require('url').pathtofileurl(resolvedpath)
// 首先对代码进行打包
const bundled = await bundleconfigfile(resolvedpath, true)
dependencies = bundled.dependencies
// ts + esm
if (ists) {
fs.writefilesync(resolvedpath + '.js', bundled.code)
userconfig = (await dynamicimport(`${fileurl}.js?t=${date.now()}`))
.default
fs.unlinksync(resolvedpath + '.js')
debug(`ts + native esm config loaded in ${gettime()}`, fileurl)
}
// js + esm
else {
userconfig = (await dynamicimport(`${fileurl}?t=${date.now()}`)).default
debug(`native esm config loaded in ${gettime()}`, fileurl)
}
}
可以看到,首先通过 esbuild 将配置文件编译打包成 js 代码:
const bundled = await bundleconfigfile(resolvedpath, true) // 记录依赖 dependencies = bundled.dependencies
对于 ts 配置文件来说,vite 会将编译后的 js 代码写入临时文件,通过 node 原生 esm import 来读取这个临时的内容,以获取到配置内容,再直接删掉临时文件:
fs.writefilesync(resolvedpath + '.js', bundled.code)
userconfig = (await dynamicimport(`${fileurl}.js?t=${date.now()}`)).default
fs.unlinksync(resolvedpath + '.js')
以上这种先编译配置文件,再将产物写入临时目录,最后加载临时目录产物的做法,也是 aot (ahead of time)编译技术的一种具体实现。
而对于 js 配置文件来说,vite 会直接通过 node 原生 esm import 来读取,也是使用 dynamicimport 函数的逻辑,dynamicimport 的实现如下:
export const dynamicimport = new function('file', 'return import(file)')
你可能会问,为什么要用 new function 包裹?这是为了避免打包工具处理这段代码,比如 rollup 和 tsc,类似的手段还有 eval。你可能还会问,为什么 import 路径结果要加上时间戳 query?这其实是为了让 dev server 重启后仍然读取最新的配置,避免缓存。
commonjs 格式
对于 commonjs 格式的配置文件,vite 集中进行了解析:
// 对于 js/ts 均生效 // 使用 esbuild 将配置文件编译成 commonjs 格式的 bundle 文件 const bundled = await bundleconfigfile(resolvedpath) dependencies = bundled.dependencies // 加载编译后的 bundle 代码 userconfig = await loadconfigfrombundledfile(resolvedpath, bundled.code)
bundleconfigfile 函数的主要功能是通过 esbuild 将配置文件打包,拿到打包后的 bundle 代码以及配置文件的依赖 (dependencies)。而接下来的事情就是考虑如何加载 bundle 代码了,这也是 loadconfigfrombundledfile 要做的事情。
async function loadconfigfrombundledfile(
filename: string,
bundledcode: string
): promise<userconfig> {
const extension = path.extname(filename)
const defaultloader = require.extensions[extension]!
require.extensions[extension] = (module: nodemodule, filename: string) => {
if (filename === filename) {
;(module as nodemodulewithcompile)._compile(bundledcode, filename)
} else {
defaultloader(module, filename)
}
}
// 清除 require 缓存
delete require.cache[require.resolve(filename)]
const raw = require(filename)
const config = raw.__esmodule ? raw.default : raw
require.extensions[extension] = defaultloader
return config
}
loadconfigfrombundledfile 大体完成的是通过拦截原生 require.extensions 的加载函数来实现对 bundle 后配置代码的加载,代码如下:
// 默认加载器
const defaultloader = require.extensions[extension]!
// 拦截原生 require 对于`.js`或者`.ts`的加载
require.extensions[extension] = (module: nodemodule, filename: string) => {
// 针对 vite 配置文件的加载特殊处理
if (filename === filename) {
;(module as nodemodulewithcompile)._compile(bundledcode, filename)
} else {
defaultloader(module, filename)
}
}
而原生 require 对于 js 文件的加载代码如下所示。
module._extensions['.js'] = function (module, filename) {
var content = fs.readfilesync(filename, 'utf8')
module._compile(stripbom(content), filename)
}
事实上,node.js 内部也是先读取文件内容,然后编译该模块。当代码中调用module._compile 相当于手动编译一个模块,该方法在 node 内部的实现如下:
module.prototype._compile = function (content, filename) {
var self = this
var args = [self.exports, require, self, filename, dirname]
return compiledwrapper.apply(self.exports, args)
}
在调用完 module._compile 编译完配置代码后,进行一次手动的 require,即可拿到配置对象:
const raw = require(filename) const config = raw.__esmodule ? raw.default : raw // 恢复原生的加载方法 require.extensions[extension] = defaultloader // 返回配置 return config
这种运行时加载 ts 配置的方式,也叫做 jit (即时编译),这种方式和 aot 最大的区别在于不会将内存中计算出来的 js 代码写入磁盘再加载,而是通过拦截 node.js 原生 require.extension 方法实现即时加载。
至此,配置文件的内容已经读取完成,等后处理完成再返回即可:
// 处理是函数的情况
const config = await (typeof userconfig === 'function'
? userconfig(configenv)
: userconfig)
if (!isobject(config)) {
throw new error(`config must export or return an object.`)
}
// 接下来返回最终的配置信息
return {
path: normalizepath(resolvedpath),
config,
// esbuild 打包过程中搜集的依赖
dependencies
}
总结
下面我们来总结一下 vite 配置解析的整体流程和加载配置文件的方法:
首先,vite 配置文件解析的逻辑由 resolveconfig 函数统一实现,其中经历了加载配置文件、解析用户插件、加载环境变量、创建路径解析器工厂和生成插件流水线这几个主要的流程。
其次,在加载配置文件的过程中,vite 需要处理四种类型的配置文件,其中对于 esm 和 commonjs 两种格式的 ts 文件,分别采用了aot和jit两种编译技术实现了配置加载。
到此这篇关于一文弄懂vite 配置文件的文章就介绍到这了,更多相关vite 配置文件内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论