onmyway133 / blog

🍁 What you don't know is what you haven't learned
https://onmyway133.com/
MIT License
679 stars 33 forks source link

How to use export all and export default in Javascript #964

Open onmyway133 opened 10 months ago

onmyway133 commented 10 months ago

In JavaScript, particularly in modules used in frameworks like React, export statements are used to expose code—such as functions, classes, or constants—from one module so that they can be imported and reused in other modules.

export *

The export * syntax is used to re-export all exportable members from the imported module. It's a way to aggregate exports from several modules into a single module. For example, let's say we have a couple of modules, each exporting some components:

// file: buttons.js
export const PrimaryButton = () => {/* ... */};
export const SecondaryButton = () => {/* ... */};

// file: inputs.js
export const TextInput = () => {/* ... */};
export const CheckboxInput = () => {/* ... */};

Now, suppose we want to group these exports into a single index.js file for easier import elsewhere:

// file: index.js
export * from './buttons';
export * from './inputs';

Now, in another file, you can import everything from index.js like this:

import { PrimaryButton, SecondaryButton, TextInput, CheckboxInput } from './index';

This is a convenient pattern for organizing exports, especially for large libraries or components grouped by their functionality.

export { default }

When using export { default }, you're explicitly exporting the default export of a module. It's a way to re-export the default export under the same or a different name. Let's illustrate with an example module that has a default export:

// file: MyComponent.js
const MyComponent = () => {/* ... */}
export default MyComponent;

If you want to re-export this default export from an index.js file, you can do this:

// file: index.js
export { default as MyComponent } from './MyComponent';

OR:

// file: index.js
export { default } from './MyComponent';

The first method gives you a named export of the default export, while the second one simply re-exports it as default. In another file, you can import MyComponent as follows:

// Named import due to the named re-export
import { MyComponent } from './index';

// OR if you used the second re-export version
import MyComponent from './index';

In summary, export * is about re-exporting all named exports from a module, while export { default } is specific to re-exporting the default export of a module. These patterns help to manage and organize module exports in a scalable and maintainable way, which is particularly useful when building React applications with many components.