前言
上一节我们提供的svite.config.ts
配置文件没有相应的TypeScript
类型定义,这对开发者是不友好的
本节我们通过提供一个defineConfig
函数来优化这个问题
源码获取
更新进度
公众号:更新至第15
节
博客:更新至第6
节
尝试
这似乎很简单,在packages\vite\src\node\config.ts
中导出defineConfig
函数,该函数用作向用户提供类型支持
export function defineConfig(config: UserConfig): UserConfig {
return config;
}
为了达到这个目的,还需要在packages\vite\src\node\index.ts
中导出UserConfig
export * from "./config";
接着在playground\config\svite.config.ts
中导入并使用,理论上就大功告成了
import {
defineConfig } from "svite";
export default defineConfig({
server: {
},
root: "",
});
此时启用该用例,会发现如下报错
Dynamic require of "fs" is not supported
原因分析
该报错说明我们正在esm
模块的执行过程中使用require
语法,这似乎有点不可思议,因为我们在packages\vite\rollup.config.ts
文件中定义的output.format
确实是esm
格式,打包结果如下所示
import {
resolve } from 'node:path';
import {
existsSync } from 'node:fs';
import {
build } from 'esbuild';
const DEFAULT_CONFIG_FILES = ["svite.config.ts"];
async function buildBoundle(fileName) {
...
}
async function loadConfigFromBoundled(code, resolvedPath) {
...
}
function defineConfig(config) {
return config;
}
async<