如何验证生成的包符合 conditional exports 规范?

解读

在国内前端面试中,面试官抛出“验证包是否符合 conditional exports 规范”这一问,表面看是考察 Node.js 模块解析,实质是在检验候选人是否具备“从构建到发布”的闭环质量意识。Gulp 作为流式构建工具,最终产物要交给 npm 消费;若 exports 字段写错,下游项目轻则无法 import,重则 Tree-Shaking 失效、线上体积膨胀。因此,验证环节必须嵌入 Gulp 的 CI 流水线,而不是事后人工比对。面试官希望听到:

  1. 你能在 Gulp 任务里自动跑官方校验器;
  2. 你能模拟真实引用场景(ESM/CJS/TypeScript/Bundler)做黑盒测试;
  3. 你能把结果吐回 Gulp 流,失败即终止发布。

知识点

  1. conditional exports 语法:"exports" 字段支持 "."、"./feature"、"import"/"require"/"node"/"default"、"types" 等条件分支,顺序写错即失效。
  2. 官方校验器:@npmcli/package-json(npm 8+ 内置)与 publint(npm 包)可静态扫描字段合法性;Node.js core 提供 --experimental-policy 做运行时校验。
  3. Gulp Vinyl 流:通过 gulp.src 读取 package.json,在内存中改写再回写文件系统,保证校验的是“即将发布”的版本而非源码。
  4. 黑盒测试:使用 createRequire、import()、esbuild、webpack、ts-node 五种运行时真实解析入口,若任一失败即视为不符合规范。
  5. CI 卡点:借助 gulp-if + process.env.CI 实现本地只警告、CI 直接抛错,防止带病的包进入私有 npm 仓库。

答案

我通常把验证拆成两步,全部写进 gulpfile.mjs,让 gulp publish 串行执行:

第一步,静态校验:

import { src, dest, series } from 'gulp';
import through2 from 'through2';
import publint from 'publint';
import { promises as fs } from 'fs';

function lintExports() {
  return src('package.json', { base: '.' })
    .pipe(through2.obj(async (file, _, cb) => {
      const report = await publint({ cwd: file.dirname });
      const fatal = report.messages.some(m => m.type === 'error');
      if (fatal) {
        const msg = report.messages.map(m => m.content).join('\n');
        return cb(new Error(`❌ publint: ${msg}`));
      }
      console.log('✅ publint passed');
      cb(null, file);
    }));
}

第二步,运行时黑盒:

import { pathToFileURL } from 'url';
import { createRequire } from 'module';

async function runtimeTest() {
  const pkg = JSON.parse(await fs.readFile('package.json', 'utf8'));
  const entry = pkg.exports?.['.']?.import || pkg.module || pkg.main;
  if (!entry) throw new Error('缺少入口');

  // ESM 解析
  await import(pathToFileURL(require.resolve(entry)).href);
  // CJS 解析
  createRequire(import.meta.url)(entry);
  console.log('✅ runtime import/require passed');
}

把两步串成 export.series(lintExports, runtimeTest),并在 gulp publish 前执行。
任何一步抛错,Vinyl 流中断,后续 npm publish 不会执行,从而保证发到 cnpm 或私有仓库的包 100% 符合 conditional exports 规范。

拓展思考

  1. 多入口场景:若包提供 /feature 子路径,可在 runtimeTest 里循环 pkg.exports 所有 key,动态生成测试用例,避免手写遗漏。
  2. TypeScript 类型:"types" 条件必须排在 "import"/"require" 之前,否则 tsc 会报 “types is not the first condition”。可在 lintExports 里用正则强制顺序校验。
  3. 体积监控:把 publint 与 size-limit 结合,同一 Gulp 任务内既验规范又看体积,一旦新增 export 导致体积增幅超 5% 直接报警。
  4. 国内镜像同步:公司使用 cnpm 私服时,在 Gulp 流里再调一次 npm info <pkg>@<version> --registry=https://registry.npmmirror.com,确认私服已同步且 exports 字段未被私服篡改,才算真正闭环。