Export

Inside a module, you can choose to not export anything. Or, you can export primitive values, functions, classes, and objects. There are two types of exports—named exports and default exports. You can have multiple named exports in the same module but only a single default export in that module.

In the following examples, we will create a user.js module that exports the User class, a tasks.js module that tracks the count of total completed tasks, and a roles.js module that exports role constants.

Let's have a look at user.js file:

1. export default class User {
2. constructor (name, role) {
3. this.name = name;
4. this.role = role;
5. }
6. };

In this module, we export the User class inline as the default export by placing the keywords export and default in front of it. Instead of declaring an export inline, you can declare the User class first and then export it at the bottom, or anywhere that is at the top level in the module, even before the User class.

Let's have a look at roles.js file:

1. const DEFAULT_ROLE = 'User';
2. const ADMIN = 'Admin';
3. export {DEFAULT_ROLE as USER, ADMIN};

In this module, we create two constants and then export them using named exports in a list by wrapping them in curly brackets. Yes, in curly brackets. Don't think of them as exporting an object. And as you can see in line 3, we can rename things during export. We can also do the rename with import too. We will cover that shortly.

Let's have a look at tasks.js file:

1. console.log('Inside tasks module');
2. export default function completeTask(user) {
2. console.log(`${user.name} completed a task`);
3. completedCount++;
4. }
5. // Keep track of the count of completed task
6. export let completedCount = 0;

In this module, in line 2, we have a default export of the completeTask function and a named export of a completedCount variable in line 6.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.182.73