概念概述
浏览器原生 ES 模块(Native ES Modules in the Browser)指的是:原生 ES 模块为浏览器提供真正的模块图,具有静态导入、延迟执行与按模块缓存,取代仅依赖打包器的假设。
从更严格的定义看,An ES module is a JavaScript file whose imports and exports form a static dependency graph that the browser resolves and evaluates, with module code running in strict mode and its own scope. 该概念在工程实践中的价值,在于它能帮助团队用统一的语言描述一个具体的质量属性或设计约束,从而在评审与协作中减少歧义。
为什么需要它
It underpins modern build tooling, dynamic imports for code splitting, and import maps for bare-specifier resolution. 它与 Import Maps for Module Resolution、CSS Cascade Layers、CSS Container Queries 等概念经常一起出现,用于解决相近的工程问题。理解它的适用场景,有助于在多种备选方案之间做出有依据的取舍,而不是凭直觉选择技术方案。
常见误解
- modules execute in the order their script tags appear
- a module’s bindings are copied by value at import time
需要避免的反模式
- mixing classic and module scripts without tracking execution order
- assuming server code can load a .js file that the browser treats differently
实践要点
- Module scripts are deferred by default, execute once per graph even if imported many times, and evaluate dependencies before their dependents, giving a deterministic order.
- Imported bindings are live references rather than copies, so a mutation to an exported variable is observable in the importing module, unlike destructured values.
- Bare specifiers such as a package name are not valid URLs in the browser until an import map maps them, and dynamic import returns a promise for code defined in a separate module.
参考来源
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules