Explain Codes LogoExplain Codes Logo

When should I use curly braces for ES6 import?

javascript
es6-imports
naming-conventions
refactoring
Alex KataevbyAlex Kataev·Aug 14, 2024
TLDR

Curly braces in ES6 import are utilized for named exports, which are the individual features offered by a module. Meanwhile, no braces are required for a module's default export—a module's beefy, star player.

Named (with braces):

// The curly squad import { map, reduce } from 'lodash';

Default (no braces):

// One pro player import React from 'react';

Both types combined:

// The star player and his buddies import React, { useState } from 'react';

Fundamentally, the gist of understanding when to use curly braces is knowing the architecture of the module you're importing from. Use any name you prefer for default exports, while for named exports, stick to the names declared in the module.

Effective naming strategies

Maintain a keen eye on your naming conventions to prevent unexpected "undefined" errors. If your imported names don't align with your exported ones, it's like calling your cat "Fido"—talk about an identity crisis!

Writing efficient ES6 imports

Your bundle size matters as much as your waist size after Thanksgiving! Use selective importing when you merely need certain parts of a module. This practice reinforces the overall efficiency of your bundle size. So stay fit, coder!

Valuing clarity and easy refactoring

Refactoring without tears is what named exports offer. Changes to your export names are mirrored across your import statements, making your refactor more akin to a sweet serenade than a nerve-wrecking nightmare.

TypeScript and aliasing

Programmers in TypeScript land can reap the benefits of named exports too. With better hands-on refactoring and stringent compile-time checks, aliasing becomes a nifty tool in your coding arsenal.

The all-importing move

Sometimes, you might feel the urge to import all available exports from a module. Use import * as Alias for this, but remember—moderation is key!

Making sense out of standard cases

Here's a tour through the common scenarios of ES6 imports you usually encounter:

Lone ranger defaults

// Ride solo, default export! import Feature from 'FeatureModule';

The specific squad

// When you need more than one weapon from your arsenal import { FeatureA, FeatureB } from 'UtilitiesModule';

Mixing and matching

// Party time with default and named exports import Library, { Feature1, Feature2 as LongNameShort } from 'LibraryModule';

The all-you-can-import buffet

// When hunger knows no bounds! But remember, only useful if you can digest it all. import * as Utils from 'UtilitiesModule';