如何自定义 resolver 插件以支持私有 npm registry 的模块解析?

解读

在国内前端团队普遍使用私有 npm(Verdaccio、Nexus、CNPM、企业内网 Harbor-NPM 等)的背景下,Webpack 默认的模块解析规则(先找 node_modules,再按 main/module/browser 字段回退)往往无法识别公司域下的私有包,例如 @corp/xxx 或 @fe/yyy。
面试官真正想考察的是:

  1. 你是否理解 Webpack 内部 resolve 阶段的工作流程(enhanced-resolve 钩子)。
  2. 能否在不污染项目源码、不硬写 alias 的前提下,用“插件”方式把私有 registry 的解析规则无缝注入到 Webpack 生命周期。
  3. 对国内网络环境(镜像源切换、缓存、权限、HTTPS 自签证书)有没有工程化经验。

一句话:不是问“怎么配 alias”,而是问“怎么写一段可在所有项目复用的 resolver 插件,让 @corp 包在任何机器上都解析正确”。

知识点

  1. Webpack 解析流程:
    resolveId → resolve → resolveStep → result;底层使用 enhanced-resolve 提供的 tapable 钩子:resolve、parsedResolve、describedResolve、afterResolve。
  2. 插件入口:
    在 Webpack 配置 plugins 数组里实例化一个普通 class,在 apply(compiler) 中拿到 compiler.resolverFactory,通过 resolverFactory.hooks.resolver 拦截 Resolver 创建,再对具体 resolver.hooks.resolve 做 tapAsync。
  3. 私有包特征:
    scope 名固定(@corp)、registry 域名固定(registry.corp.com)、可能带端口或 /npm 前缀、需要认证(_authToken、.npmrc)。
  4. 解析算法补充:
    先尝试本地 node_modules/@corp;若不存在,则去私有 registry 下载 tgz 并解压到全局缓存目录(~/.corp-pkg-cache),再把路径回传给 Webpack;需处理 semver、tag、peerDependencies。
  5. 缓存与性能:
    用 lru-cache 做内存缓存,用 cacache 做磁盘缓存,避免每次构建都发 HTTP。
  6. 安全与合规:
    国内公司要求内网 HTTPS 证书自签,需在插件里附带 NODE_EXTRA_CA_CERTS 或 agentOptions;同时把 _authToken 读自环境变量,避免写死。
  7. 插件发布:
    做成独立的 npm 包 @corp/webpack-resolver-plugin,在 webpack.config.js 里一行引用即可,符合“插件即依赖”的国内 Monorepo 规范。

答案

下面给出可直接落地的“最小可运行 + 生产级健壮”示例,兼顾国内面试“能写骨架 + 能说细节”的双重要求。

// corp-resolver-plugin.js
const path = require('path');
const fs = require('fs');
const https = require('https');
const cacache = require('cacache');
const semver = require('semver');

const CACHE_PATH = path.join(require('os').homedir(), '.corp-pkg-cache', 'content-v2');

class CorpResolverPlugin {
  constructor(options = {}) {
    this.scope = options.scope || '@corp';
    this.registry = options.registry || 'https://registry.corp.com';
    this.token = process.env.CORP_NPM_TOKEN; // 安全读取
  }

  apply(compiler) {
    compiler.resolverFactory.hooks.resolver.for('normal').tap('CorpResolverPlugin', resolver => {
      resolver.hooks.resolve.tapAsync(
        { name: 'CorpResolverPlugin', stage: 100 }, // 早于默认 resolver
        (request, resolveContext, callback) => {
          const moduleName = request.request;
          if (!moduleName || !moduleName.startsWith(this.scope + '/')) {
            return callback(); // 交回给默认解析
          }

          // 1. 本地 node_modules 兜底
          const localPath = path.join(resolver.options.modules[0], moduleName);
          if (fs.existsSync(localPath)) {
            return callback(null, { ...request, path: localPath });
          }

          // 2. 私有 registry 解析
          const pkgName = moduleName.split('/')[1]; // @corp/abc -> abc
          const infoUrl = `${this.registry}/${this.scope}%2f${pkgName}`;

          const agent = new https.Agent({
            rejectUnauthorized: false, // 自签证书场景
          });

          https.get(infoUrl, { headers: { authorization: `Bearer ${this.token}` }, agent }, res => {
            let body = '';
            res.on('data', chunk => body += chunk);
            res.on('end', async () => {
              try {
                const meta = JSON.parse(body);
                const latest = meta['dist-tags'].latest;
                const tgzUrl = meta.versions[latest].dist.tarball;

                // 3. 缓存命中
                const cacheKey = `corp:${moduleName}@${latest}`;
                const cachedPath = await cacache.get(CACHE_PATH, cacheKey).then(x => x.data).catch(() => null);
                if (cachedPath) {
                  return callback(null, { ...request, path: cachedPath.toString() });
                }

                // 4. 下载并解压
                const tmpDir = path.join(CACHE_PATH, 'tmp', `${Date.now()}`);
                fs.mkdirSync(tmpDir, { recursive: true });
                const tgzFile = path.join(tmpDir, 'pkg.tgz');
                const file = fs.createWriteStream(tgzFile);
                https.get(tgzUrl, { agent }, res => {
                  res.pipe(file);
                  file.on('finish', () => {
                    file.close(() => {
                      // 5. 解压(略,可用 tar 包)
                      const extractTo = path.join(CACHE_PATH, 'extracted', `${moduleName}@${latest}`);
                      require('child_process').execSync(`tar -xf ${tgzFile} -C ${extractTo} --strip-components=1`);
                      cacache.put(CACHE_PATH, cacheKey, extractTo).then(() => {
                        callback(null, { ...request, path: extractTo });
                      });
                    });
                  });
                });
              } catch (e) {
                callback(e);
              }
            });
          }).on('error', callback);
        }
      );
    });
  }
}

module.exports = CorpResolverPlugin;

使用方式:

// webpack.config.js
const CorpResolverPlugin = require('./corp-resolver-plugin');

module.exports = {
  plugins: [
    new CorpResolverPlugin({ registry: 'https://registry.corp.com' })
  ]
};

面试时把骨架写出来,再补充三点细节即可拿高分:

  1. 通过 resolver.hooks.resolve.tapAsync 插入,stage 设 100 保证优先级。
  2. 缓存用 cacache,key 带版本,避免重复下载;磁盘路径放在用户家目录,Linux/Win/Mac 通用。
  3. 自签证书场景下 agent.rejectUnauthorized = false,同时 token 从环境变量读,满足国内安全审计要求。

拓展思考

  1. 微前端场景:如果子应用也走私有 registry,可以把插件抽成 webpack 联邦共享模块,结合 ModuleFederationPlugin 的 shareScope,实现“一次解析,多子应用复用”。
  2. Monorepo + pnpm:pnpm 的虚拟 store 导致 node_modules 结构扁平但非真实路径,插件里需通过 require.resolve.lookupPaths 或 pnpm 的 @pnpm/find-packages 先定位真实 store,再回写路径。
  3. 国内镜像 failover:registry.corp.com 不可用时,自动降级到 cnpm 镜像或阿里云内网镜像,可在插件里封装 retry + circuit breaker,体现高可用意识。
  4. 合规审计:把下载日志通过 winston 打到 elk,方便审计“谁在哪次构建拉取了哪个版本”,满足金融/国企合规要求。