Search code examples
javascriptnode.jsbabeljscommonjs

export default grammar Babel ES6


Using Babel, I'm having trouble importing the following module:

// mongoose_helpers.js

const r_string = {
  type: String,
  required: true
}

const r_number = {
  type: Number,
  required: true
}

export default { r_string, r_number }

this way:

import { r_string, r_number } from './mongoose_helpers'

Which throws an error in the file I'm importing.

However it works if I do this:

const r_string = {
  type: String,
  required: true
}

(...)

const helpers = { r_string, r_number }

export default helpers

and then

import helpers from './mongoose_helpers'

Just curious what is wrong with the first approach ?


Solution

  • export default { r_string, r_number } is basically exporting an object with two keys (r_string, r_number)

    it will work with import helpers from './mongoose_helpers'

    When you say import { r_string, r_number } from './mongoose_helpers' you are telling JS that you want two named exports from your modules. This is not a destructuring syntax. In order to use this, you need to specify the exports like this

    export const r_string = ...
    export const r_number = ...
    

    The ultimate article on ES6 modules: http://www.2ality.com/2014/09/es6-modules-final.html