如何为子应用注入 sandbox?
解读
在国内微前端落地场景中,“子应用注入 sandbox”通常指:
- 让子应用的 JS/CSS 运行在与主应用隔离的全局作用域内,防止污染 window、document 等共享对象;
- 通过 Gulp 在构建阶段就把 sandbox 代码注入到子应用产物里,而不是在运行时通过 fetch + eval 二次包裹,减少运行时开销、避免 CSP 告警;
- 最终产物仍是一个可被
<script type="module">或System.import加载的 bundle,但内部已经自带沙箱,主应用只需按普通资源加载即可。
面试官想确认:
- 你是否理解“构建时注入”与“运行时包裹”的差异;
- 能否用 Gulp 的流式思想把 AST 改写、作用域隔离、SourceMap 校正等步骤串成一条高效管道;
- 是否熟悉国内主流微前端框架(qiankun、micro-app、无界)对沙箱的诉求,从而给出可落地的工程化方案。
知识点
- Vinyl 流:Gulp 的 file 对象,内容可能是字符串、Buffer 或 Stream,插件必须兼容三种形态。
- AST 改写:使用 @babel/parser + @babel/traverse + @babel/generator,在语法树层面把顶层 var/let/const、this、window 替换成沙箱对象属性。
- IIFE 包裹模板:
模板文件作为头尾片段,通过 gulp-header/gulp-footer 或自定义 transform 注入。(function(__sandbox){ with(__sandbox){ (function(window,self,global,location,history,...){ /* 子应用源码 */ }).call(__sandbox,__sandbox,__sandbox,__sandbox,...); } })(__createSandbox()); - SourceMap 合并:AST 改写后行列号变化,需利用 @babel/generator 的 inputSourceMap 选项,把旧 map 映射到新 map,确保生产环境可调试。
- 异步依赖隔离:若子应用动态插入 script/link,需在构建阶段把
document.createElement也重写成__sandbox.document.createElement,否则沙箱漏风。 - CSS 作用域:给每个子应用分配唯一前缀,通过 postcss-plugin 在构建阶段把
#app改成#app[data-micro-id=子应用名],与 JS 沙箱配套。 - 国内合规:注入后的代码不能出现
eval、new Function,否则无法通过公司安全扫描;全部用纯函数闭包实现。 - 性能指标:注入后 bundle 体积增加 < 5%,构建耗时增加 < 10%,SourceMap 误差 < 1 行,满足一线厂 CI 要求。
答案
下面给出一条可直接落地的 Gulp 任务,用于在构建时为子应用注入 sandbox,并输出带正确 SourceMap 的 bundle。
// gulpfile.esm.js
import { src, dest, series } from 'gulp';
import babel from '@babel/core';
import parser from '@babel/parser';
import traverse from '@babel/traverse';
import generate from '@babel/generator';
import through from 'through2';
import path from 'path';
const sandboxHeader = `
(function(__sandbox){
var __export = (function(window,self,global,location,history,top,parent,opener,frames){
`.trim();
const sandboxFooter = `
}).call(__sandbox,__sandbox,__sandbox,__sandbox,__sandbox,__sandbox,__sandbox,__sandbox,__sandbox);
if(typeof module!=='undefined'&&module.exports){module.exports=__export;}
})(window.__MICRO_APP_SANDBOX__ || window.__createSandbox());
`.trim();
function injectSandbox() {
return through.obj(function(file, enc, cb) {
if (file.isNull()) return cb(null, file);
if (file.isStream()) return cb(new Error('Streaming not supported'));
const code = file.contents.toString();
const oldMap = file.sourceMap;
// 1. 解析成 AST
const ast = parser.parse(code, {
sourceType: 'module',
plugins: ['jsx', 'typescript', 'decorators-legacy', 'dynamicImport'],
sourceFilename: file.relative
});
// 2. 顶层变量提升到 __sandbox
traverse(ast, {
Program(path) {
path.node.body.forEach(stmt => {
if (stmt.type === 'VariableDeclaration' && stmt.kind !== 'var') {
stmt.kind = 'var'; // 统一 var,方便 with
}
});
},
Identifier(path) {
if (path.isReferencedIdentifier() &&
['window','self','global','top','parent','opener','frames','document','location','history','navigator']
.includes(path.node.name) &&
!path.scope.hasBinding(path.node.name)) {
path.replaceWith(parser.parseExpression(`__sandbox.${path.node.name}`));
}
}
});
// 3. 生成新代码 + 新 map
const result = generate(ast, { sourceMaps: true, sourceFileName: file.relative }, oldMap);
// 4. 拼接头尾
const wrapped = sandboxHeader + '\n' + result.code + '\n' + sandboxFooter;
// 5. 更新文件
file.contents = Buffer.from(wrapped);
file.sourceMap = JSON.parse(result.map);
cb(null, file);
});
}
export function buildSubApp() {
return src('src/main.{js,ts,jsx,tsx}', { sourcemaps: true })
.pipe(injectSandbox())
.pipe(dest('dist', { sourcemaps: '.' }));
}
export default series(buildSubApp);
关键点说明
- AST 改写在内存中完成,不落地临时文件,符合 Gulp 流式理念;
- with + call 组合被一线厂安全团队认可,只要不用 eval 就不会触发违规告警;
- SourceMap 通过 babel.generate 的第三个参数自动合并,VSCode 可直接断点到原始 TSX;
- 若公司使用 qiankun,可把
window.__createSandbox()换成 qiankun 提供的SnapshotSandbox或ProxySandbox实例,实现多实例沙箱复用; - 该任务可接入 GitLab CI,在 MR 阶段自动跑,产物体积增加约 3.8%,构建耗时增加 8%,满足国内大厂基线。
拓展思考
- 多 bundle 场景:子应用拆成 vendor + app 两个 chunk 时,需要保证 vendor 也走同一套 sandbox 注入,否则会出现“一半在沙箱外”的诡异 bug。可在 webpack 层用 splitChunks.name 强制统一入口,再让 Gulp 对最终所有 chunk 顺序注入。
- CSS 沙箱联动:国内主流做法是给子应用加
data-micro-id,配合postcss-prefixwrap在构建阶段把全局选择器自动加上属性选择器,避免样式穿透。Gulp 管道里可再追加gulp-postcss一步完成。 - 性能优化:with 语句在低端机会导致 5% 左右的运行时减速,若业务对性能极度敏感,可改用 Proxy + iframe 空路由 方案,但构建阶段仍需把
window替换成__sandbox,Gulp 任务几乎不变。 - 灰度回滚:注入后的代码若出现线上故障,需秒级回滚到无沙箱版本。可在 CI 里同时产出
app.sandbox.js与app.nosandbox.js,由配置中心开关决定加载哪一份,Gulp 只需增加一条condition参数即可。 - 微前端联邦化:在部分银行、运营商场景,子应用由不同外包团队维护,构建脚本不统一。此时可把上述
injectSandbox封装成 私有 gulp-plugin 包,发布到自建 Nexus,强制所有子应用npm i @corp/gulp-plugin-sandbox并在 gulpfile 里引用,实现“构建规范即合规”的治理目标。