Search code examples
reactjsimportecmascript-6commonjs

CommonJS imports vs ES6 imports


Here are two examples of using a non-default export. The first uses commonjs syntax, and the second uses es6. Why does the first example work, but not the second?

// commonjs --- works!
var ReactRouter = require('react-router')
var Link = ReactRouter.Link


// es6 --- doesn't work!
import ReactRouter from 'react-router'
var Link = ReactRouter.Link

I understand that I can use import { Link } from 'react-router' instead, but I'm just trying to wrap my head around how each import differs.


Solution

  • import ReactRouter only imports the default export. It does not import an object of named exports which is what you're attempting to achieve in your ES6 code. If there is no default export in the module, this ReactRouter will be undefined.

    As stated, import { Link } from 'react-router' is the dedicated syntax for importing a single named export.

    If you want to import all named exports into an object, you can use the import..as syntax:

    import * as ReactRouter from 'react-router';
    var Link = ReactRouter.Link
    

    MDN has a super-helpful list of all the different types of imports and how they work.