1. 前言

大家好,我是若川。我倾力持续组织了一年多源码共读,感兴趣的可以加我微信 lxchuan12 参与。另外,想学源码,极力推荐关注我写的专栏《学习源码整体架构系列》,目前是掘金关注人数(4.7k+人)第一的专栏,写有20余篇源码文章。

2. 看开源项目学习是怎样的步骤?

看一个开源仓库,第一步一般是看 README.md 和 contributing.md 贡献指南文档。

README.md 中一般有提到贡献指南文档的链接的。贡献指南文档就是为了让别人参与项目贡献。

而贡献指南写了很多关于参与项目开发的信息。比如怎么跑起来,项目目录结构是怎样的。怎么投入开发,需要哪些知识储备等。

第二步的克隆下来。按照贡献指南文档,把项目跑起来。

3. 如何调试 vue3 源码

我们这次来学调试 vue3 源码,看 vue3 源码[1]仓库 contributing.md[2]。

contributing.md 部分内容

Development Setup

You will need Node.js[3]version 16+, and PNPM[4]version 7+.

We also recommend installing ni[5] to help switching between repos using different package managers. ni also provides the handy nr command which running npm scripts easier.

After cloning the repo, run:

$ pnpm i # install the dependencies of the project

关于上方提到的 ni,我曾经写过源码文章,可供参考。

尤雨溪推荐神器 ni ,能替代 npm/yarn/pnpm ?简单好用!源码揭秘!

从贡献指南中,我们可以得知一些信息,那么先来克隆项目安装依赖。

git clone https://github.com/vuejs/core.git

cd core

# 安装依赖

pnpm i

4. 使用 vitest vscode 扩展的调试方式

安装vitest vscode 扩展链接[6]、vitest vscode 扩展 github[7]

安装vitest-runner vscode 扩展链接[8]、vitest-runner vscode 扩展 github[9]

vitest-vscode 安装

debugger.png

debugger-test.png

// packages/vue/__tests__/index.spec.ts

import { vi } from 'vitest'

import { EMPTY_ARR } from '@vue/shared'

import { createApp, ref, nextTick, reactive } from '../src'

describe('compiler + runtime integration', () => {

  it('should support runtime template compilation', () => {

    const container = document.createElement('div')

    const App = {

      template: `{{ count }}`,

      data() {

        return {

          count: 0

        }

      }

    }

 // 可以按住 alt + 鼠标左键点击 跳转到函数,提前断点好想断点的地方

    createApp(App).mount(container)

    expect(container.innerHTML).toBe(`0`)

  })

  // 省略若干代码

}

如下图 gif 图所示,就是调试 vue 源码了。

gif 图调试源码

关于 gif 图中顶部各个按钮的作用,我曾经写过一篇文章新手向:前端程序员必学基本技能——调试JS代码

通过开源项目的测试用例调试源码,它的优点在于不用打包、更接近源码,测试覆盖率高的开源项目,可以只针对某项功能做针对性调试,看测试用例的过程中也能直接学会使用。而这种调试方式,可能是大部分人从未使用过的调试源码方式,因为大多数人可能没学过测试框架。

Vue 源码的测试用例现在改成了 Vitest[10]。

同理可得,如果开源项目是使用 Jest 测试框架,可以安装 `Jest`[11]、`Jest Runner`[12]vscode 插件。

5. 通过生成 sourcemap 调试

5.1 如何生成 sourcemap

贡献指南的文档 contributing.md[13] 中有写:

Build with Source Maps

Use the --sourcemap or -s flag to build with source maps. Note this will make the build much slower.

pnpm run build -s

执行后,所有的都生成了 sourcemap 文件,如下图所示。

vue sourcemap

通过 sourcemap 文件,可以找到原始文件信息。

我们可以在根目录下的 package.json 中,看到有一个启动服务的命令。

{

  "private": true,

  "version": "3.3.0-alpha.4",

  "packageManager": "pnpm@7.26.0",

  "type": "module",

  "scripts": {

    "serve": "serve",

  },

}

这时再在命令行终端,执行这条命令,启动服务。

pnpm run serve

serve.png

浏览器打开 http://localhost:5000 可以找到相应路径。

比如我们打开这个源码中有的 todomvc 例子,来调试。http://localhost:64085/packages/vue/examples/composition/todomvc

// packages/vue/examples/composition/todomvc.html