Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 486
Jonny Avatar asked May 05 '16 12:05

Jonny


People also ask

What is the difference between CommonJS and ES6?

While CommonJS and ES6 modules share similar syntax, they work in fundamentally different ways: ES6 modules are pre-parsed in order to resolve further imports before code is executed. CommonJS modules load dependencies on demand while executing the code.

Is Es modules better than CommonJS?

Apart from being the standard for JavaScript modules, the ES module syntax is also much more readable compared to require() . Web developers who primarily write JavaScript on the client will have no issues working with Node. js modules thanks to the identical syntax.

Is CommonJS obsolete?

It is not deprecated.

Can I use import with CommonJS?

Importing from ESM and CommonJS to CommonJS Since require() is synchronous, you can't use it to import ESM modules at all! In CommonJS you have to use require syntax for other CommonJS modules and an import() function (distinct from the import keyword used in ESM!), a function that returns a promise, to import ESM.


1 Answers

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.

like image 168
CodingIntrigue Avatar answered Oct 02 '22 04:10

CodingIntrigue