【问题标题】:How can I export a class with multiple static methods如何导出具有多个静态方法的类
【发布时间】:2019-05-27 11:30:24
【问题描述】:

我正在尝试在 node.js 中导出此类:

export class className {
  static method1(param1) {
    // do something
  }

  static method2(param1, param2) {
    // do something
  }
}

但它让我在终端出现以下错误:

complete_path.....\node_modules@babel\runtime\helpers\esm\classCallCheck.js:1 [2] (function (exports, require, module, __filename, __dirname) { 导出默认函数 _classCallCheck(instance, Constructor) { [2]
^^^^^^ [2] [2] SyntaxError: Unexpected token export [2] at new 脚本 (vm.js:83:7) [2] at createScript (vm.js:267:10) [2] at Object.runInThisContext (vm.js:319:10) [2] 在 Module._compile (内部/模块/cjs/loader.js:685:28) [2] 在 Object.Module._extensions..js (internal/modules/cjs/loader.js:733:10) [2] 在 Module.load (internal/modules/cjs/loader.js:620:32) [2]
在 tryModuleLoad (internal/modules/cjs/loader.js:560:12) [2] 在 Function.Module._load (internal/modules/cjs/loader.js:552:3) [2]
在 Module.require (internal/modules/cjs/loader.js:658:17) [2] 在 需要(内部/模块/cjs/helpers.js:22:18)[2] [nodemon] 应用程序 崩溃 - 在开始之前等待文件更改...

【问题讨论】:

    标签: node.js class export


    【解决方案1】:

    Node.js 尚不支持 export 关键字。你必须使用exportsmodule.exports

    在您的情况下,您应该使用module.exports:

    module.exports = class className {
      static method1(param1) {
        // do something
      }
    
      static method2(param1, param2) {
        // do something
      }
    }
    

    有关exportsmodule.exports 之间区别的更多信息,我建议您使用post

    【讨论】:

      【解决方案2】:

      使用module.exports 而不是export

      module.exports = class className {
      
       static method1(param1) {
           // do something
       }
      
      
       static method2(param1, param2) {
           // do something
       }
      
      }
      

      【讨论】:

      • 感谢 Mayur,但现在收到“SyntaxError: Unexpected token export”。在从 '../../folder/exportedClassFile' 导入 { className } 期间;
      • @AlamgirKhan 纯 node.js 不使用“import ... from ...”。你应该使用“const ...= require(...)”
      • @BogdanSurai 我也尝试过 required ,但同样的问题。并且对于导入,我使用的是 babel 所以而不是使用module.exports ={ and then functions ... 的类,即使我使用import * as someObj from '../../folder/thatFileName'; 也可以正常工作....但不知道为什么我们不能导出类​​我也尝试了@Mayur @Yannick Loriot 方法!
      • 我认为你不能使用import { className }。试试import className from classFile。或者,module.exports = {className}。然后,import {className} from classFile
      猜你喜欢
      • 2012-04-19
      • 1970-01-01
      • 1970-01-01
      • 2015-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-16
      • 1970-01-01
      相关资源
      最近更新 更多