CommonJS import vs ES6 import

Here are two examples of using the 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 instead of import { Link } from 'react-router' I can use import { Link } from 'react-router' , but I'm just trying to wrap my head in how each import is different.

+7
import ecmascript-6 reactjs commonjs
source share
1 answer

import ReactRouter imports only the default export. It does not import the object with the specified export, which is what you are trying to achieve in ES6 code. If there is no default export in the module, this ReactRouter will be undefined .

As stated, import { Link } from 'react-router' is a 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-useful list of all types of imports and how they work.

+9
source share

All Articles