美文网首页
ES6 Module

ES6 Module

作者: 李欢li | 来源:发表于2018-10-29 12:46 被阅读0次

    ES Module 是在 ECMAScript 6 中引入的模块化功能。模块功能主要由两个命令构成,分别是 export 和 import。export 命令用于规定模块的对外接口,import 命令用于输入其他模块提供的功能。
    那么在遇到 import 和 export 时发生了什么呢?ES6 的模块加载机制可以概括为四个字 一静一动 。
    一静:import 静态执行
    一动:export 动态绑定
    import 静态执行是指,import 命令会被 JavaScript 引擎静态分析,优先于模块内的其他内容执行。
    export 动态绑定是指,export 命令输出的接口,与其对应的值是动态绑定关系,通过该接口可以实时取到模块内部的值。
    其使用方式如下:

    //foo.js
    console.log('foo is running');
    import {bar} from './bar'
    console.log('bar = %j', bar);
    setTimeout(() => console.log('bar = %j after 500 ms', bar), 500);
    console.log('foo is finished');
    
    //bar.js
    console.log('bar is running');
    export let bar = false;
    setTimeout(() => bar = true, 500);
    console.log('bar is finished');
    
    //执行 node foo.js 时会输出如下内容:
    bar is running
    bar is finished
    foo is running
    bar = false
    foo is finished
    bar = true after 500 ms
    

    import 命令是在编译阶段执行,在代码运行之前先被 JavaScript 引擎静态分析,所以优先于 foo.js 自身内容执行。同时我们也看到 500 毫秒之后也可以取到 bar 更新后的值也说明了 export 命令输出的接口与其对应的值是动态绑定关系。这样的设计使得程序在编译时就能确定模块的依赖关系,这是和 CommonJS 模块规范的最大不同。还有一点需要注意的是,由于 import 是静态执行,所以 import 具有提升效果即 import 命令的位置并不影响程序的输出。
    export 和 export default
    在一个文件或模块中,export 可以有多个,export default 仅有一个, export 类似于具名导出,而 default 类似于导出一个变量名为 default 的变量。同时在 import 的时候,对于 export 的变量,必须要用具名的对象去承接,而对于 default,则可以任意指定变量名

    循环依赖

    //foo.js
    console.log('foo is running');
    import {bar} from './bar'
    console.log('bar = %j', bar);
    setTimeout(() => console.log('bar = %j after 500 ms', bar), 500);
    export let foo = false;
    console.log('foo is finished');
    
    //bar.js
    console.log('bar is running');
    import {foo} from './foo';
    console.log('foo = %j', foo)
    export let bar = false;
    setTimeout(() => bar = true, 500);
    console.log('bar is finished');
    
    //执行 node foo.js 时会输出如下内容:
    bar is running
    foo = undefined
    bar is finished
    foo is running
    bar = false
    foo is finished
    bar = true after 500 ms
    

    foo.js 和 bar.js 形成了循环依赖,但是程序却没有因陷入循环调用报错而是执行正常,这是为什么呢?还是因为 import 是在编译阶段执行的,这样就使得程序在编译时就能确定模块的依赖关系,一旦发现循环依赖,ES6 本身就不会再去执行依赖的那个模块了,所以程序可以正常结束。这也说明了 ES6 本身就支持循环依赖,保证程序不会因为循环依赖陷入无限调用。虽然如此,但是我们仍然要尽量避免程序中出现循环依赖,因为可能会发生一些让你迷惑的情况。注意到上面的输出,在 bar.js 中输出的 foo = undefined ,如果没注意到循环依赖会让你觉得明明在 foo.js 中 export foo = false ,为什么在 bar.js 中却是 undefined呢,这就是循环依赖带来的困惑。在一些复杂大型项目中,你是很难用肉眼发现循环依赖的,而这会给排查异常带来极大的困难。对于使用 webpack 进行项目构建的项目,推荐使用 webpack 插件 circular-dependency-plugin来帮助你检测项目中存在的所有循环依赖,尽早发现潜在的循环依赖可能会免去未来很大的麻烦。

    https://www.colabug.com/2227753.html

    相关文章

      网友评论

          本文标题:ES6 Module

          本文链接:https://www.haomeiwen.com/subject/nywmtqtx.html