且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

es6模块如何加载工作

更新时间:2022-05-30 22:53:47

p> ES6模块加载程序将获取源,确定依赖关系,并等待这些依赖关系在执行模块之前加载。所以在需求执行时,依赖关系已经在等待执行了。

The ES6 Module Loader will fetch the source, determine dependencies, and wait until those dependencies have loaded before executing the module. So by the time the require executes, the dependency is already sitting there waiting to be executed.

当通过ES6模块加载器加载CommonJS时,我们依靠静态解析需要来自源的语句,只有在需要的时候才执行源代码。

When loading CommonJS through an ES6 module loader, we rely on statically parsing out the require statements from the source, and only executing the source once those requires have loaded.

这样我们可以在浏览器中动态加载CommonJS。循环引用的处理方式与Node中处理的方式相同。

In this way we can support CommonJS in the browser loaded dynamically. Circular references are treated identically to the way they are handled in Node.

解析请求的正则表达式实际上是非常可靠和快速的,同时考虑到注释和周围令牌。请参阅 https://github.com/systemjs/systemjs/ blob / master / lib / extension-cjs.js#L10 为SystemJS使用的一个。

The regular expressions parsing out the require are actually pretty reliable and quick, while taking into account comments and surrounding tokens. See https://github.com/systemjs/systemjs/blob/master/lib/extension-cjs.js#L10 for the one used by SystemJS.

这种方法还有一个限制,动态和条件的CommonJS需要像 if(condition)require('some'+'name')没有被正确检测到。这使得CommonJS在浏览器中作为完全异步的模块格式成为必要的代价。

There is one remaining limitation with this approach and that is dynamic and conditional CommonJS requires like if (condition) require('some' + 'name') aren't detected properly. This is a necessary cost though to make CommonJS behave as a fully asynchronous module format in the browser.