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.
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.
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.
It is not deprecated.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With