简体   繁体   English

在浏览器 + Node 中,模块的作用域是什么?

[英]In browsers + Node, what is the scope of a module?

I'm wondering what the scope of a module is in both browsers and Node.我想知道模块在浏览器和 Node.js 中的范围是什么。 I'm specifically trying to understand whether a module-level variable is created once per app, or many times.我特别想了解模块级变量是为每个应用程序创建一次还是多次创建。 Is a new instance of the module created on each import, or is it the exact same module shared across all imports?是在每次导入时创建模块的新实例,还是在所有导入中共享的完全相同的模块? Many thanks!非常感谢!

There are several JS module flavours - ESM, CommonJS, AMD.有几种 JS 模块风格 - ESM、CommonJS、AMD。 Their common trait is that they are evaluated once on first import, at least under normal circumstances.它们的共同特点是它们在第一次导入时被评估一次,至少在正常情况下是这样。 Doing the opposite would make them inefficient for sharing data.反其道而行之会使它们共享数据的效率低下。

Exporting class instance is a common way to share one instance across the application without making a class a singleton.导出类实例是一种在应用程序中共享一个实例而不使类成为单例的常用方法。

The ways that can make a module be evaluated multiple times (intentionally or not) include having many copies of a module, different filename case on import in case-insensitive system, the modification of Node module cache.可以使模块被多次评估(有意或无意)的方法包括具有多个模块副本、在不区分大小写的系统中导入时的不同文件名大小写、修改节点模块缓存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM