58

What is the correct syntax to import both default and named resource from an ES6 JavaScript module?

Example:

export const defaultBrowser = 'Chrome';

export default [
  { value: 0, label: defaultBrowser },
  { value: 1, label: 'Firefox' },
  { value: 2, label: 'Safari' },
  { value: 3, label: 'Edge' },
];

How would one import that in one go?


It is not a duplicate of When should I use curly braces for ES6 import?, it is more specific, asking for a single import use-case, and not an import essay.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
wscourge
  • 10,657
  • 14
  • 59
  • 80

1 Answers1

86

The correct syntax to import both default and named exports from ES6 module is to pass the default name (whatever one wants), and named, not-default modules separated by a comma:

Example: index.js

import browsers, { otherValue } from './browsers';

in an exemplary file tree:

.
└── src
    ├── browsers.js
    └── index.js

Often encountered real life example:

import React, { useState, useEffect } from 'react';
qwertzguy
  • 15,699
  • 9
  • 63
  • 66
wscourge
  • 10,657
  • 14
  • 59
  • 80
  • 12
    `import defaultVar, { namedVar1, namedVar2 } from './your-file';` (for anybody who gets confused by the variable naming in the answer) – totymedli Jan 17 '20 at 23:59
  • 2
    *"[exemplary](https://en.wiktionary.org/wiki/exemplary#Adjective) file tree"* or *"example file tree"* (there is a difference)? – Peter Mortensen Dec 08 '20 at 10:19