ES6 Modules: Import and Export
In this lesson, we cover all the different ways to import and export functionaliities from modules in ES6.
We'll cover the following
In JavaScript ES6, you can import and export functionalities from modules. These can be functions, classes, components, constants, essentially anything you can assign to a variable. Modules can be single files or whole folders with one index file as entry point.
After we bootstrapped our application with create-react-app at the beginning, we already used several import
and export
statements in the initial files. The import
and export
statements help you to share code across multiple files. Historically there were already several solutions for this in the JavaScript environment, but it was a mess because there wasn’t a standardized method of performing this task. JavaScript ES6 added it as a native behavior eventually.
These statements embrace code splitting, where we distribute code across multiple files to keep it reusable and maintainable. The former is true because we can import a piece of code into multiple files. The latter is true because there is only one source where you maintain the piece of code.
We also want to think about code encapsulation, since not every functionality needs to be exported from a file. Some of these functionalities should only be used in files where they have been defined. File exports are basically a public API to a file, where only the exported functionalities are available to be reused elsewhere. This follows the best practice of encapsulation.
The following examples showcase the statements by sharing one or multiple variables across two files. In the end, the approach can scale to multiple files and could share more than simple variables.
The act of exporting one or multiple variables is called a named export:
Get hands-on with 1400+ tech skills courses.