When should you use curly braces for ES6 imports
September 05, 2021
When should you use curly braces for ES6 imports:
If you are writing code in javascript and if ES6 is supported in that project, you might have come across imports that are imported in files using a curly braces like:
import {functionName} from './path/to/util';
and we can also import without using any curly braces like:
import utils from './path/to/util';
Anything that we are importing in a file needs to be exported from another file. There are two types of exports:
- Named Export and
- Default Export
Named Export:
Named exports are imported using curly braces. We can export multiple things from one file as like below:
export const myConst = 10;
export const myFunc = () => {};
These exports are imported using curly braces.
import {myConst, myFunc} from './path/to/file';
or we can import these in different lines:
import {myConst} from './path/to/file';
import {myFunc} from './path/to/file';
Default export:
Default export is imported without using any curly braces. We can have only one default export in one file:
export default myFunc;
It can be imported without using any curly braces:
import myFunc from './path/to/file';
Can we have both named or default export in the same file:
We can have both named and default export in the same file. For example:
export const myConst = 10;
export const myFunc = () => {};
const anotherFunc = () => {}
export default anotherFunc;
We can import these similarly:
import {myConst, myFunc} from './path/to/file';
import anotherFunc from './path/to/file';
Renaming while importing:
We can rename while importing :
import {myConst as c} from './path/to/file';
That’s all !!