This tutorial aims to provide a comprehensive understanding of how to use import
and export
statements in JavaScript. These are powerful features that allow you to split your code into multiple, reusable modules, making your code cleaner and easier to maintain.
By the end of this tutorial, you will:
- Understand the syntax and usage of import
and export
statements.
- Know how to import and export functions, objects, or values from modules.
- Learn best practices when using these statements.
Prerequisites: Basic knowledge of JavaScript syntax and concepts are required for this tutorial.
In JavaScript, you can separate code into different files (modules) for better maintainability. To share functions, objects, or primitive values between these modules, you can use export
to share them, and import
to bring them in.
There are two types of exports: named exports (zero or more exports per module) and default exports (one per module).
// Export as declared
export const pi = 3.14159;
// All together
const gravity = 9.8;
const speedOfLight = 299792458;
export { gravity, speedOfLight };
export default function() { console.log('Hello World!'); }
{}
.import { pi, gravity } from './constants.js';
{}
.import greet from './greet.js';
Let's look at some practical examples:
constants.js
// Exports named constants
export const pi = 3.14159;
export const gravity = 9.8;
main.js
// Import named exports from "constants.js"
import { pi, gravity } from './constants.js';
console.log(pi); // Outputs: 3.14159
console.log(gravity); // Outputs: 9.8
greet.js
// Default export
export default function() { console.log('Hello World!'); }
main.js
import greet from './greet.js';
greet(); // Outputs: Hello World!
In this tutorial, you've learned how to use import
and export
to share code between JavaScript modules. Keep in mind that default exports are useful when a module only wants to export a single class or function, while named exports can be used to export several values.
For further learning, consider exploring how to use import
and export
with classes, as well as understanding the difference between importing a module vs. importing a module's content.
Create two modules: one that exports a function (default) that returns the square of a number, and another that imports and uses this function.
Create a module that exports an object (named) with properties representing different mathematical constants. Create another module that imports and uses this object.
Create a module that exports a class (default) representing a geometric shape, and another module that imports this class and instantiates an object.
Solutions and detailed explanations will be provided, along with tips for further practice to strengthen your understanding of these concepts.