Default and Named Exports from the same ES6 Module

The CommonJS module system only allowed for the export of a single object from a module. ES6 module syntax allows for a single default export and any number of named exports. Both can be included in the same module and consumed individually or together. Let’s illustrate this with a simple module example.

export const version = '1.2.30';export default version;

Though it appears that the same constant is being exported twice, this allows you to get the default export bound to version or get the named export bound to version using curly braces.

// default export
import version from './version';
// named export
import { version } from './version';

Here we are defining some color constants as well as an array of those constants.

// constantsexport const COLOR_RED = '#990000';
export const COLOR_GREEN = '#009900';
export const COLOR_BLUE = '#000099';
export default [
COLOR_RED,
COLOR_GREEN,
COLOR_BLUE
];

The named constants can be imported individually:

import { COLOR_BLUE, COLOR_RED } from './constants';

The default export can be imported directly without curly braces:

import ColorList from './constants';

Default exports and named exports can be imported together as well:

import ColorList, { COLOR_RED, COLOR_GRAY } from'./constants';

All of the color constants can be imported together or you can choose just the ones you need for a particular script.

Software dev

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store