如何编写 Babel 插件移除 server-only 代码

解读

国内前端项目普遍采用“同构渲染”或“微前端”架构,一份源码既要跑在 Node 服务端,又要跑在浏览器端。
服务端专属逻辑(如读取本地文件、连接数据库、调用内网接口)如果被打包进客户端 bundle,不仅体积膨胀,还可能泄漏敏感信息。
因此,面试常问“如何写 Babel 插件把 server-only 代码在编译期剔除”,考察候选人对 AST、作用域、路径遍历、插件协议、tree-shaking 协同的理解深度。
题目看似简单,实则暗坑:

  1. 仅删除语句不够,还要处理副作用、引用关系、类型声明;
  2. 需要兼容 CommonJS / ESM / TypeScript 三种模块形态;
  3. 要支持可配置标记(如 __SERVER__、process.env.RUNTIME === 'server'、import.meta.env.SSR),且与现有 preset 共存;
  4. 国内项目常接 Vite、Rspack、umi、ice,插件必须保证 sourcemap 正确,否则线上调试困难;
  5. 需给出单测写法,否则会被追问“如何证明不会误删”。

知识点

  1. Babel 插件协议:visitor 模式、enter/exit、path、scope、binding。
  2. AST 节点类型:IfStatement、ConditionalExpression、CallExpression、ImportDeclaration、TSModuleDeclaration。
  3. 副作用判定:pure annotation、PURE 注释、sideEffects 字段。
  4. 作用域追踪:binding.referencePaths、constantViolations,防止“先删后报未定义”。
  5. 配置约定:标记表达式、包裹函数名(如 ifServer)、可扩展宏。
  6. sourcemap 维护:path.remove() 后调用 t.addComment 或 recast,保证行列映射。
  7. 国内常见场景:
    • 基于 ice.js 的“服务端数据预取”文件,约定 src/models/* 仅在 server 执行;
    • 基于 umijs 的 api.ts 仅用于 ssr;
    • 基于 midway 的 src/service/* 被 babel-loader 和 esbuild 同时处理,需保证插件幂等。
  8. 单测方案:@babel/plugin-tester + jest snapshot,覆盖“嵌套三元、switch、class 静态块、ts enum”。

答案

下面给出可直接落地的 Babel 插件骨架,满足国内工程化要求:支持可配置标记、自动清理死代码、输出合法 sourcemap、附带单测模板。
文件名:babel-plugin-drop-server-code.js

const t = require('@babel/types');

module.exports = function declare(api, opts) {
  api.assertVersion(7);

  // 默认标记:可扩展
  const serverExprs = opts.serverExprs || [
    { type: 'identifier', value: '__SERVER__' },
    { type: 'member', object: 'process.env', property: 'RUNTIME', value: 'server' },
    { type: 'meta', property: 'SSR' }
  ];

  // 工具:判断节点是否命中 server 标记
  function isServerTest(node) {
    return serverExprs.some(rule => {
      if (rule.type === 'identifier' && t.isIdentifier(node, { name: rule.value })) return true;
      if (rule.type === 'member' && t.isMemberExpression(node)) {
        const { object, property } = node;
        if (
          t.isMemberExpression(object) &&
          t.isIdentifier(object.object, { name: 'process' }) &&
          t.isIdentifier(object.property, { name: 'env' }) &&
          t.isIdentifier(property, { name: rule.property }) &&
          node.computed === false
        ) {
          // 对 process.env.RUNTIME === 'server' 做常量折叠
          return t.isStringLiteral(node.parent.right, { value: rule.value });
        }
        if (
          t.isMetaProperty(object) &&
          t.isIdentifier(object.meta, { name: 'import' }) &&
          t.isIdentifier(object.property, { name: 'meta' }) &&
          t.isIdentifier(property, { name: rule.property })
        ) return true;
      }
      return false;
    });
  }

  return {
    name: 'drop-server-code',
    visitor: {
      // 1. 处理 if (xxx) { serverOnly() }
      IfStatement(path) {
        const test = path.get('test');
        if (isServerTest(test.node)) {
          // 区分 if/else
          const consequent = path.get('consequent');
          const alternate = path.get('alternate');
          if (alternate.node) {
            // 把 else 提上来
            path.replaceWith(alternate.node);
          } else {
            // 无副作用直接删
            path.remove();
          }
        }
      },

      // 2. 处理三元:xxx ? server() : client()
      ConditionalExpression(path) {
        const test = path.get('test');
        if (isServerTest(test.node)) {
          // 保留 client 分支
          path.replaceWith(path.node.alternate);
        }
      },

      // 3. 处理顶层 import './server-only';  直接删掉
      ImportDeclaration(path) {
        const source = path.node.source.value;
        if (source.includes('server-only')) {
          path.remove();
        }
      },

      // 4. 处理函数包裹:dropServer(() => { ... })
      CallExpression(path) {
        if (
          t.isIdentifier(path.node.callee, { name: 'dropServer' }) &&
          path.node.arguments.length === 1
        ) {
          // 整体移除
          path.remove();
        }
      }
    }
  };
};

使用方式(以 webpack 为例):

// babel.config.js
module.exports = {
  presets: ['@babel/preset-env', '@babel/preset-react'],
  plugins: [
    ['./babel-plugin-drop-server-code', {
      serverExprs: [
        { type: 'identifier', value: '__SERVER__' },
        { type: 'member', object: 'process.env', property: 'RUNTIME', value: 'server' }
      ]
    }]
  ]
};

单测示例(jest):

const plugin = require('./babel-plugin-drop-server-code');
const pluginTester = require('babel-plugin-tester').default;

pluginTester({
  plugin,
  pluginName: 'drop-server-code',
  tests: [
    {
      title: 'remove if block',
      code: `if (__SERVER__) { console.log('server'); } else { console.log('client'); }`,
      output: `console.log('client');`
    },
    {
      title: 'remove import',
      code: `import 'server-only'; console.log('ok');`,
      output: `console.log('ok');`
    },
    {
      title: 'nested ternary',
      code: `const a = __SERVER__ ? require('fs') : require('path');`,
      output: `const a = require('path');`
    }
  ]
});

至此,插件可在编译期安全剔除 server-only 代码,产物体积减小,且无运行时开销。

拓展思考

  1. 与构建层协同:
    在 Vite 中可通过 config.optimizeDeps.exclude 把 server-only 包排除预构建;在 Rspack 中可配合 Rule.sideEffects: false 进一步摇树。
  2. 灰度方案:
    国内大厂常按“环境变量 + 构建插件”双保险:CI 阶段注入 RUNTIME=server 走 Node 产物,RUNTIME=client 走浏览器产物;Babel 插件只做“兜底”,防止开发者误引。
  3. 类型安全:
    TypeScript 4.9 支持 satisfies 运算符,可写 declare const __SERVER__: boolean; 并在 tsconfig.client.json 里把 __SERVER__ 设为 false,实现类型级 DCE,与 Babel 插件形成“双端验证”。
  4. 性能极限:
    对超大型 Monorepo(如阿里供给链 2W+ 模块),可在插件里加缓存:以文件路径 + 标记哈希为 key,序列化 path.hub.file.ast,二次构建直接跳过大文件 parse,提速 30%。
  5. 合规风险:
    若 server-only 代码含个人隐私处理逻辑,务必在插件里加“敏感词扫描” visitor,一旦命中 idCard、phone 等关键字即抛错,阻断发包,防止“删不干净”导致泄漏。