第 65 期 - npm install 原理全解析
logoFRONTALK AI/12月27日 16:33/阅读原文

摘要

本文讲述了 npm install 中 ActualTree 和 IdealTree 两棵树的构建流程、比较、Diff 树操作、package.json 和 package - lock.json 文件更新,还有本地调试方法和参考文档等内容。

一、整体流程

1. npm install 流程涉及两棵树

2. ActualTree 创建流程

async # loadActual (options) {
    // 创建根 Node 节点
    this.# actualTree = await this.# loadFSNode({ path: this.path });
    // 解析本地 package - lock.json 文件内容
    const meta = await Shrinkwrap.load();
    this.# actualTree.meta = meta;
    // 递归遍历 Node 节点,构建 Node 节点树
    await this.# loadFSTree(this.# actualTree);
}

3. IdealTree 创建流程

async # initTree () {
    let root;
    // 获取项目的 package.json 文件内容
    const pkg = await rpj(this.path + '/package.json');
    // 创建根 Node 节点
    root = await this.rootNodeFromPackage(pkg);
    // 遍历 package - lock.json 中的依赖,创建其对应的子 Node 节点,并建立父子引用关系
    return this.loadVirtual({ root });
}

二、数据引用图谱

1. ActualTree

2. IdealTree

三、核心代码

1. Reifier.reify

async reify (options) {
    // 创建 ActualTree 和 IdealTree
    await this[_loadTrees](options);
    // 对比 ActualTree 和 IdealTree 的差异,创建 Diff 树
    await this[_diffTrees]();
    // 遍历 Diff 树中 Node 节点,创建其对应的目录,下载其对应的产物,执行其 script 脚本命令,例如 postinstall
    await this[_reifyPackages]();
    // 更新 package.json 配置文件内容和保存 package - lock.json 文件
    await this[_saveIdealTree](options);
}

2. 创建 ActualTree 相关函数

3. 创建 IdealTree 相关函数

4. 对比 ActualTree 和 IdealTree 差异相关函数

5. 遍历 Diff 树相关函数

6. 更新 package.json 和保存 package - lock.json 相关函数

四、本地调试

五、参考文档

 

扩展阅读

Made by 捣鼓键盘的小麦 / © 2025 Front Talk 版权所有