Node.js和ES6中的module.exports与export默认

Node module.exports和ES6 之间有什么区别export default我试图弄清楚为什么export default在Node.js 6.2.2中尝试出现“ __不是构造函数”错误

什么有效

'use strict'
class SlimShady {
  constructor(options) {
    this._options = options
  }

  sayName() {
    return 'My name is Slim Shady.'
  }
}

// This works
module.exports = SlimShady

什么工作

'use strict'
class SlimShady {
  constructor(options) {
    this._options = options
  }

  sayName() {
    return 'My name is Slim Shady.'
  }
}

// This will cause the "SlimShady is not a constructor" error
// if in another file I try `let marshall = new SlimShady()`
export default SlimShady
伽罗2020/03/19 11:07:43

您需要在项目中正确配置babel以使用export default和export const foo

npm install --save-dev @babel/plugin-proposal-export-default-from

然后在.babelrc中添加以下配置

"plugins": [ 
       "@babel/plugin-proposal-export-default-from"
      ]