21

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.

2
  • 1
    I think you have a typo in your CommonJS too, shouldn't it be var Link = ReactRouter.Link? Commented May 5, 2016 at 12:55
  • Yes, though that wasn't the issue
    – Jonny
    Commented May 5, 2016 at 12:57

1 Answer 1

23

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.

1
  • So var ReactRouter = require('react-router') is equivalent to import * as ReactRouter from 'react-router'?
    – Jonny
    Commented May 5, 2016 at 13:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.