【问题标题】:Is ES6 `export class A` equivalent to `module.exports = A`?ES6 `export class A` 是否等同于`module.exports = A`?
【发布时间】:2015-05-06 15:27:33
【问题描述】:

当我看到 Babel 编译的代码时,它们似乎并不等价。 其实前者转化为exports.A = A,不等于module.exports = A(可能是module.exports.A = A?)

那么有没有 ES6 风格的module.export =?或者语法仍然在 ES6 中?或者 ES6 不再推荐这种语法?

【问题讨论】:

    标签: node.js ecmascript-6


    【解决方案1】:

    你可以使用

    export default class A {
    
    }
    

    或者

    class A {
    
    }
    
    export default A;
    

    将导出为

    exports["default"] = A;
    module.exports = exports["default"];
    

    在互操作部分here.中有一个解释

    为了鼓励使用 CommonJS 和 ES6 模块,在导出没有其他导出的默认导出时,除了exports["default"],还会设置module.exports

    【讨论】:

      【解决方案2】:

      您可以在 Node v6 中使用以下内容:

      "use strict" 
      
      class ClassName {
       // class code
      }
      
      module.exports = ClassName
      

      将上述文件另存为ClassName.js

      将其导入另一个文件 Test.js:

      "use strict"
      var ClassName= require('./ClassName.js');
      var obj = new ClassName( Vars . . . );
      

      更多信息:

      Here's an article on exporting classes from modules in Node v6

      【讨论】:

        【解决方案3】:

        babel6 不支持export default Amodules.export=A

        你应该添加一个plugin

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-11-19
          • 1970-01-01
          • 2017-03-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-06-10
          相关资源
          最近更新 更多