zoukankan      html  css  js  c++  java
  • es6 module与CommonJS规范的区别?

    es6:import / export / export default

    CommonJS:require/ module.exports / exports 

    1.module.exports,exports同属于CommonJS模块规范。在NodeJS中,exports === module.exports,exports是module.exports的引用,于是exports指向的是module.exports,exports的存在是辅助module.exports取属性。

    所以你去直接令exports = xxx是没用的

    原因如下:

    console.log(exports === module.exports);//true
    var exports = module.exports;//node里面默认存在这句代码
    exports.name = '"swk"';
    exports.age = 18;
    exports.hello = function ()
    {
        console.log("hello Nodejs!");
    }
    
    /**上面的代码等同于 */
    module.exports = {
        name: 'swk',
        age: 18,
        hello: function (param)
        {
            console.log('我是swk');
        }
    }
    
    //exports = xxx相当于修改exports指向的内存地址的对象,对module.exports毫无影响,所以在require('xxx')的时候就会报错
    // 在node中exports的作用只是辅助module.exports取数据,require('xxx')实际上是从module.exports处取数据的
    // 在js里面基本数据类型用栈存储,复杂数据类型用堆存储。一个对象它的引用地址保存在栈区,而对象本身保存在堆区,而这常常会导致很多问题
    // exports.xxx = yyy属于CommonJS1的规范,而module.exports = zzz属于CommonJS2的规范

     总结:

    与 es6模块完全不同,CommonJS 模块输出的是值的缓存,不存在动态更新。

    Nodejs是基于CommonJS规范实现的,NodeJS不支持 import 和 export。

    浏览器不支持CommonJS语法,所以需要用 Browserify 或 Webpack 等打包工具进行打包。Browserify 的原理其实就是实现了下面的变量。

    浏览器不兼容CommonJS的根本原因在于缺少4个Node.js的环境变量:

    • module
    • exports
    • require
    • global

    es6 兼容以上所有语法,当然需要 webpack + babel 来支撑。已经有浏览器支持es6语法。

    尽管es6兼容以上所有语法,但需要注意:在webpack打包的时候,可以在js文件中混用 require 和 export。但是不能混用 import 以及 module.exports。

    更详细的讲解可以查阅该博客:https://juejin.im/post/5badebedf265da0af609bdad,个人觉得不错

  • 相关阅读:
    git中Please enter a commit message to explain why this merge is necessary.
    用$(this)选择其下带有class的子元素
    将某页面中ajax中获取到的信息放置到sessionStorage中保存,并在其他页面调用这些数据。
    返回顶部黑科技
    对于div里面内容过大根据长度或者宽度进行适配,然后可以滚轮缩放的功能
    vue runtime报错问题
    webpack简单配置
    input type=color 设置颜色
    vue统一注册组件
    vue模板字符串写法
  • 原文地址:https://www.cnblogs.com/ft039x/p/10173034.html
Copyright © 2011-2022 走看看