javascriptreactjsecmascript-6babeljsfbjs

Import statement and Babel


I'm defining two constants using keyMirror from Facebook's fbjs.

// file1.js
import keyMirror from 'fbjs/lib/keyMirror'
export default keyMirror({
    CONST1: null,
    CONST2: null,
})

then import them in file2.js:

// file2.js
import { CONST1, CONST2 } from './file1'
console.log(CONST1) // undefined

their values can't be resolved. If I change file2.js like so:

// file2.js
import constants from './file1'
console.log(constants.CONST1) // CONST1

it works fine. What's wrong with it? I'm using Babel 6 with babel-preset-es2015 to run the scripts.


Solution

  • Your imports do not match, if you export a default export, you must import a default. If you want to import using named exports, then you need to export using named exports.

    For

    import { CONST1, CONST2 } from './file1'
    

    to work, you'd need

    export let {CONST1, CONST2} = keyMirror({
        CONST1: null,
        CONST2: null,
    });
    

    The { CONST1, CONST2 } after import in ES6 module syntax is unrelated to destructuring, so you should not think of it as pulling properties off of the default export. Instead, think of it as a list of names to import from the module.

    Your solution would potentially have worked with Babel 5, but it was still invalid, even then. You can see this answer for more of an explanation of that.

    Each ES6 module exports a set of exports, with default being special-cased for simplicity.

    import constants from './file1';
    

    is short for

    import {default as constants} from './file1';
    

    and

    export default keyMirror({
        CONST1: null,
        CONST2: null,
    })
    

    is essentially short for

    var temp = keyMirror({
        CONST1: null,
        CONST2: null,
    });
    export {temp as default};