源码解析-nrm

513 阅读1分钟

项目名称

nrm

功能说明

NPM注册表管理器,在不同注册表之间快速切换:例如cnpm、nj、淘宝

github源码地址

github.com/Pana/nrm

对应源码

git sha: master下的e267d44

代码中文注释

github.com/GreenMashim…

本地开发流程

克隆仓库

git clone https://github.com/Pana/nrm.git

切换到master分支

git checkout master

重置到指定sha节点

git reset --hard e267d44

安装依赖

npm install

链接到本机全局下,方便调试

npm link

查看版本号

nrm --version

模块架构图

源码目标结构说明

.
├── LICENSE              版权说明
├── README.md            项目介绍及使用
├── cli.js               主入口文件,package.json中的bin指定
├── hooks.js             https://github.com/Pana/nrm/pull/58,对应这条ISSUE
├── package-lock.json
├── package.json         npm包管理
├── registries.json      默认可选择的npm源
└── yarn.lock

功能分析

执行 nrm list

function onList () {
    getCurrentRegistry(function (cur) {
        // cur当前选中的源,显示的时候添加*号
        var info = [''];
        // 默认源列表 + .nrmrc配置的源列表
        var allRegistries = getAllRegistry();
        const keys = Object.keys(allRegistries);

        const len = Math.max(...keys.map(key => key.length)) + 3;

        Object.keys(allRegistries).forEach(function (key) {
            var item = allRegistries[key];
            // 如果当前源已经选中,则前面添加*号
            var prefix = equalsIgnoreCase(item.registry, cur) && item[FIELD_IS_CURRENT] ? '* ' : '  ';
            info.push(prefix + key + line(key, len) + item.registry);
        });

        info.push('');
        // 显示在Terminal上的信息
        /**
        info = [
            '',
            '  npm -------- https://registry.npmjs.org/',
            '  yarn ------- https://registry.yarnpkg.com/',
            '  tencent ---- https://mirrors.cloud.tencent.com/npm/',
            '  cnpm ------- http://r.cnpmjs.org/',
            '  taobao ----- https://registry.npm.taobao.org/',
            '  nj --------- https://registry.nodejitsu.com/',
            '  npmMirror -- https://skimdb.npmjs.com/registry/',
            '  edunpm ----- http://registry.enpmjs.org/',
            ''
            ]
         */
        printMsg(info);
    });
}

执行 nrm use taobao

详情请看 onUse方法

推荐

这个库源码量不大,推荐直接(github.com/GreenMashim…)查看感兴趣的方法实现