如何注入沙箱全局变量
解读
“沙箱全局变量”在前端工程里通常指:
- 编译阶段给代码注入一个“看起来是全局、实际只在当前作用域生效”的标识符;
- 运行阶段该变量对业务代码透明,却不会被真正挂载到
window/global,从而避免污染全局命名空间,也利于单元测试、微前端、SSR 等场景。
Babel 作为编译器,天然承担“改写 AST→生成新代码”的职责,因此“注入沙箱全局变量”99% 的场景会落到“写插件”上:在遍历 AST 时,把“自由变量”重定向到我们伪造的局部绑定,或在模块顶部插入一条const $global = ...的声明。
面试官问这道题,想确认三件事:
- 你是否理解 Babel 插件的完整工作流(parse→traverse→generate);
- 能否正确区分
scope与binding,防止变量提升或重复声明; - 是否知道国内主流场景(小程序、微前端、Jest 单元测试、Electron 渲染层)对“沙箱”的真实诉求。
知识点
@babel/core的插件协议:visitor对象 +pre/post钩子。path.scope的三种绑定方式:
a.scope.rename(oldName, newName)—— 安全重命名;
b.scope.generateUidIdentifier(name)—— 生成唯一标识符;
c.scope.push({ id, init })—— 直接插入局部变量。- 常见全局对象在 AST 中的表现形式:
Identifier(name="window")/MemberExpression(object="global", property="process")。 - 沙箱形状:
- 编译期沙箱:仅改源码,运行期仍跑在宿主全局,靠“局部变量覆盖”实现隔离;
- 运行期沙箱:配合
new Function()、with、iframe、vm模块等,再加 Babel 注入变量,实现真正的运行隔离。
- 国内特殊场景:
- 微信小程序找不到
window,需要把window重定向到wx或自定义globalRef; - 微前端 qiankun 要求子应用把
window.$subApp作为“假全局”,但 Babel 编译时不能出现var $subApp = window.$subApp这种死循环; - Jest 27+ 默认启用了 vm 沙箱,若源码里写了
global.ENV = xxx,测试会报错,需要 Babel 插件把global映射到jestGlobal。
- 微信小程序找不到
答案
下面给出一份可直接落地、经生产验证的 Babel 7 插件骨架,实现“把源码里所有自由变量 GLOBAL_ENV 注入为沙箱局部变量,且运行期不挂 window”。
需求假设:
- 运行环境不提供
GLOBAL_ENV,需要编译期注入; - 不能出现
var GLOBAL_ENV = window.GLOBAL_ENV这种回指; - 兼容 ES Module 与 CommonJS;
- 插件要支持参数
{ env: { api: 'https://api.xxx.com' } }。
插件文件 babel-plugin-sandbox-global.js:
const { declare } = require('@babel/helper-plugin-utils');
module.exports = declare((api, opts) => {
api.assertVersion(7);
const { env = {} } = opts;
const globalId = 'GLOBAL_ENV';
return {
name: 'sandbox-global',
visitor: {
Program(path, state) {
// 1. 生成唯一局部变量,防止与用户代码冲突
const local = path.scope.generateUidIdentifier(globalId);
// 2. 创建初始化字面量
const init = api.types.valueToNode(env);
// 3. 插入到模块顶部,使用 const 声明,保证块级作用域
path.unshiftContainer('body', [
api.types.variableDeclaration('const', [
api.types.variableDeclarator(local, init)
])
]);
// 4. 遍历所有引用到 GLOBAL_ENV 的节点,重定向到局部变量
path.traverse({
Identifier(innerPath) {
if (
innerPath.node.name === globalId &&
innerPath.isReferencedIdentifier() &&
!innerPath.scope.hasBinding(globalId) // 确保不是用户自己声明的
) {
innerPath.node.name = local.name;
}
}
});
}
}
};
});
使用方式(babel.config.js):
module.exports = {
presets: ['@babel/preset-env'],
plugins: [
['./babel-plugin-sandbox-global', {
env: { api: 'https://api.xxx.com', _isSandbox: true }
}]
]
};
编译前源码:
console.log(GLOBAL_ENV.api);
编译后产物:
const _GLOBAL_ENV = { api: "https://api.xxx.com", _isSandbox: true };
console.log(_GLOBAL_ENV.api);
至此完成“沙箱全局变量”注入:
- 运行期不存在
window.GLOBAL_ENV,也不会污染全局; - 业务代码无感知,零成本迁移;
- 插件仅 30 行,可随 CI 统一下发,满足国内云构建、小程序构建、微前端构建三套流水线。
拓展思考
- 如果沙箱要求“运行期才真正隔离”,可把上述插件再包一层
vm.runInNewContext,把const _GLOBAL_ENV注入到新的global对象,实现“编译+运行”双隔离,适用于低代码平台动态脚本。 - 对于 TypeScript 项目,需同时提供
d.ts声明declare const GLOBAL_ENV: { api: string },否则 IDE 会报找不到变量;可以把插件做成babel-preset,并在 preset 里自动写入临时.d.ts文件,做到“零配置”。 - 国内 SSR(Next.js、Umi SSR)场景下,服务端没有
window,客户端又有window,可以利用babel-plugin-transform-define区分typeof window分支,把GLOBAL_ENV注入成“服务端纯对象 + 客户端代理对象”,实现同构。 - 若需要“按需注入”而不是全部模块都插一条声明,可在插件里加
exclude正则,或利用babel-plugin-import的customName机制,把import { env } from '@sandbox/global'自动重写到局部变量,兼顾 Tree-Shaking。