Understanding Qiankun Sandbox Mechanisms and JavaScript Isolation
This article explains the three sandbox types used by Qiankun—SnapshotSandbox, LegacySandbox, and ProxySandbox—detailing how they isolate global variables, the underlying code transformation that enables this isolation, common pitfalls with implicit global declarations, and a practical fix using MicroApp's plugin system.
Qiankun provides three sandbox implementations—SnapshotSandbox, LegacySandbox, and ProxySandbox—to isolate micro‑frontend applications from the host page.
SnapshotSandbox
It creates a shallow copy of the host window object, stores the key‑value pairs in a hash map, and restores the original state by re‑applying the map during unmount.
LegacySandbox
Instead of diffing the entire window on each unmount, it records changes incrementally using addedMap , prevMap , and newMap whenever a property is added or updated, leveraging ES6 Proxy for detection.
ProxySandbox
Each micro‑app receives its own fakeWindow object. Modifications to native properties affect the real window , while other properties are stored in fakeWindow . When the app becomes inactive, its fakeWindow is saved for later reuse, eliminating the need for explicit environment restoration.
Isolation Implementation
Qiankun wraps the micro‑app's JavaScript in an IIFE that receives window , self , and globalThis as parameters, binds the function to window.proxy , and executes it with eval . This makes statements like window.a = 1 operate on window.proxy.a , achieving isolation.
Common Pitfall: Implicit Global Declarations
When code declares a function or variable without attaching it to window (e.g., add = (a, b) => a + b ), the function is not bound to window.proxy , causing add is undefined errors during evaluation.
Practical Fix with MicroApp Plugin
MicroApp offers a plugin system that can rewrite problematic code before execution. For example, a loader can replace var abc = with window.abc = to ensure globals are correctly scoped to the sandbox.
Conclusion
Qiankun's three sandbox strategies provide different trade‑offs between performance and isolation. By wrapping code in a bound IIFE and optionally using MicroApp's code‑modifying plugins, developers can reliably prevent global variable pollution across micro‑frontends.
Rare Earth Juejin Tech Community
Juejin, a tech community that helps developers grow.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.