In ES6, using curly braces for importing a single module can introduce unexpected behavior. To clarify when to use and avoid curly braces, let's examine the distinction between default and named exports.
Default Export
When importing a single module without curly braces, you're essentially importing the default export. Default exports are declared as:
export default <value>;
In the example provided, initialState.js contains a default export for the initialState object. Therefore, you can access it without curly braces:
import initialState from './todoInitialState';
Named Export
If you need to import a specific exported value, you should use curly braces. Named exports are declared as:
export const <identifier> = <value>;
In the TodoReducer.js example, you're trying to access the todo named export:
import { todo } from './todoInitialState';
Using Curly Braces vs. Avoiding Them
The rule of thumb is to use curly braces when importing named exports and avoid them when importing default exports. Here's a summarized breakdown:
Use curly braces:
Avoid curly braces:
Example
Consider the following example:
// A.js export default MyComponent; export const ChildComponent = () => {};
To import these exports:
Default export (MyComponent):
import MyComponent from './A';
Named export (ChildComponent):
import { ChildComponent } from './A';
By understanding the difference between default and named exports, you can correctly determine when to use curly braces for single module imports in ES6.
The above is the detailed content of Curly Braces in ES6 Single Module Imports: When to Use Them and When Not To?. For more information, please follow other related articles on the PHP Chinese website!