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

node.js Node.js

逆天Davaid

2020-03-19

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

第2283篇《Node.js和ES6中的module.exports与export默认》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
伽罗 2020.03.19

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

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

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

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

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android