vite源码调试
一、fork vite仓库
fork后方便做注释,这样可以将注释提交便于以后查阅。当然也可以省略这一步。
二、克隆代码
git clone git@github.com:<github name>/vite.git
pnpm install
1
2
2
代码克隆到本地后执行 pnpm install
安装依赖。
三、 运行项目
vite
源码通过pnpm workspace
进行管理,其代码放置在packages/vite
目录下,进入到该目录,查看package.json
中的scripts
:
{
...
"scripts": {
"dev": "rimraf dist && rollup -c -w",
"build": "rimraf dist && npm run lint && run-s build-bundle build-types",
"build-bundle": "rollup -c",
"build-types": "run-s build-temp-types patch-types roll-types",
"build-temp-types": "tsc --emitDeclarationOnly --outDir temp/node -p src/node",
"ci-build": "rimraf dist && run-s build-bundle build-types",
"patch-types": "ts-node scripts/patchTypes.ts",
"roll-types": "api-extractor run && rimraf temp",
"lint": "eslint --ext .ts src/**",
"format": "prettier --write --parser typescript \"src/**/*.ts\"",
"prepublishOnly": "npm run build"
}
...
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
因为vite
是使用ts
编写,实际使用时需要打包编译成js,而要调试源码就得有sourcemap
进行映射。在scripts
中build-bundle
与dev
仅差一个-w
参数,查看对应rollup.config.js
:
const createNodeConfig = (isProduction) => {
/**
* @type { import('rollup').RollupOptions }
*/
const nodeConfig = {
...
output: {
...sharedNodeOptions.output,
// dev模式下生成sourcemap
sourcemap: !isProduction
}
...
}
export default (commandLineArgs) => {
// 传入watch代表dev模式
const isDev = commandLineArgs.watch
const isProduction = !isDev
return [
envConfig,
clientConfig,
createNodeConfig(isProduction),
...(isProduction ? [terserConfig] : [])
]
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
可以看到添加-w
参数后其实就代表是dev环境,此时会输出sourcemap,并监听文件变化。所以我们执行一下:
pnpm run dev
1
执行完后,当前目录下生成了dist文件夹,其中包含打包后的js以及sourmap文件。
四、 链接包
vite是作为npm包来使用的,如果想使用本地源码可以通过link指令建立一个软链接到全局:
pnpm link --global
// 成功后会打印一下文案
/Users/chengjiewen/Library/pnpm/global/5:
+ vite 2.9.8 <- ../../../../Documents/code/vite源码学习/vite/packages/vite
1
2
3
4
5
2
3
4
5
五、 调试代码
vite已经准备好,现在可以开始调试了。首先我们建一个本地项目:
pnpm create vite vite-test -- --template vanilla
cd vite-test
pnpm install
1
2
3
4
2
3
4
安装完依赖后此时我们需要将依赖中的vite替换为我们本地link的包,所以先删除node_modules中的vite,然后在项目根目录执行一下指令:
pnpm link --global vite
1
此时再查看node_modules中的vite会发现已经变为本地的源码了。
我们在源码中打几个断点,然后在vscode的javascript debug terminal中运行我们的vite-test项目:
pnpm run dev
1
执行上面的指令就可以进入到断点了。
同时可以在vite指令后面加上debug参数,这样会打印出辅助日志,帮助理解:
"scripts": {
"dev": "vite --debug",
"build": "vite build",
"preview": "vite preview"
},
1
2
3
4
5
2
3
4
5
到此,准备工作就完成了。
参考资料: