Introduction
Unlock the power of JavaScript modules and elevate your coding skills! This comprehensive guide provides step-by-step explanations and hands-on examples to help you understand and leverage the versatility of JavaScript modules. From named exports to default exports and mixed exports, learn the various techniques to organize and structure your code effectively. Follow along with practical examples, and by the end, you’ll be equipped to create modular, maintainable JavaScript applications.
JavaScript modules are a way to organize and structure code in JavaScript by encapsulating code into separate files, making it more modular and maintainable. Modules help in breaking down a large application into smaller, manageable pieces, and they allow you to reuse code across different parts of your project.
Here’s an explanation of JavaScript modules with examples:
Exporting from a Module:
In a module, you can export variables, functions, or classes to make them accessible in other modules.
You can use the export keyword for this.
Example: math.js
// math.js export const add = (a, b) => a + b; export const subtract = (a, b) => a - b;
Importing in Another Module:
To use the exported values from a module in another module, you can use the import statement.
Example: main.js
// main.js import { add, subtract } from './math.js'; console.log(add(5, 3)); // Output: 8 console.log(subtract(10, 4)); // Output: 6
Default Export:
You can also have a default export in a module. This is useful when you want to export a single value or function as the default export.
Example: logger.js
// logger.js const logMessage = (message) => console.log(message); export default logMessage;
Example: main.js
// main.js import logMessage from './logger.js'; logMessage('Hello, world!'); // Output: Hello, world!
Importing Everything:
You can import all exported values from a module using the * wildcard.
Example: main.js
// main.js import * as math from './math.js'; console.log(math.add(5, 3)); // Output: 8 console.log(math.subtract(10, 4)); // Output: 6
CommonJS vs. ES6 Modules:
Node.js traditionally uses CommonJS modules, which use require() and module.exports for importing and exporting.
However, with the advent of ECMAScript 6 (ES6), the import and export syntax has become the standard for browser-based JavaScript and is also supported in Node.js.
// CommonJS example // math.js module.exports = { add: (a, b) => a + b, subtract: (a, b) => a - b, }; // main.js const math = require('./math.js'); console.log(math.add(5, 3)); // Output: 8 console.log(math.subtract(10, 4)); // Output: 6
In modern applications, it’s recommended to use ES6 modules for consistency and compatibility across different environments.
Let’s go through the step-by-step process of creating a JavaScript module and then importing it.
Step 1: Create the Module File
Create a new JavaScript file for your module.
Let’s call it math.js.
// math.js export const add = (a, b) => a + b; export const subtract = (a, b) => a - b;
In this example, we’ve defined two functions (add and subtract) and exported them using the export keyword.
Step 2: Create the Main File
Create another JavaScript file where you want to use the module.
Let’s call it main.js.
// main.js import { add, subtract } from './math.js'; console.log(add(5, 3)); // Output: 8 console.log(subtract(10, 4)); // Output: 6
In this file, we use the import statement to bring in the add and subtract functions from the math.js module.
Step 3: HTML File
Create an HTML file that includes your main JavaScript file.
<!-- index.html --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Module Example</title> </head> <body> <script type="module" src="main.js"></script> </body> </html>
Note the type=”module” attribute in the script tag. This is required for ES6 module scripts.
Step 4: Run the Application
Open the HTML file in a web browser.
You can do this by double-clicking the HTML file or by hosting it on a local server.
Open the browser’s developer console to see the output.
Step 5: View Output
In JavaScript, there are several ways to export values from a module.
Here are the main types of exports along with code examples:
Example: math.js
// math.js export const add = (a, b) => a + b; export const subtract = (a, b) => a - b;
Example: main.js
// main.js import { add, subtract } from './math.js'; console.log(add(5, 3)); // Output: 8 console.log(subtract(10, 4)); // Output: 6
A module can have a default export, which is used for exporting a single value or function. When importing, you can choose any name for the default import.
Example: logger.js
// logger.js const logMessage = (message) => console.log(message); export default logMessage;
Example: main.js
// main.js import logMessage from './logger.js'; logMessage('Hello, world!'); // Output: Hello, world!
Example: utils.js
// utils.js export const multiply = (a, b) => a * b; export const divide = (a, b) => a / b; // Default export const square = (x) => x * x; export default square;
Example: main.js
// main.js import square, { multiply, divide } from './utils.js'; console.log(square(4)); // Output: 16 console.log(multiply(5, 3)); // Output: 15 console.log(divide(10, 2)); // Output: 5
You can export all values from a module as properties of a single object using the * wildcard.
Example: math.js
// math.js export const add = (a, b) => a + b; export const subtract = (a, b) => a - b;
Example: main.js
// main.js import * as math from './math.js'; console.log(math.add(5, 3)); // Output: 8 console.log(math.subtract(10, 4)); // Output: 6
These are the main types of exports in JavaScript modules. Depending on your use case, you can choose the appropriate export style to structure your code effectively.
complete code example in html with explanation
math.js
// math.js export const add = (a, b) => a + b; export const subtract = (a, b) => a - b;
logger.js
// logger.js const logMessage = (message) => console.log(message); export default logMessage;
utils.js
// utils.js export const multiply = (a, b) => a * b; export const divide = (a, b) => a / b; // Default export const square = (x) => x * x; export default square;
main.js
// main.js import { add, subtract } from './math.js'; import logMessage from './logger.js'; import square, { multiply, divide } from './utils.js'; console.log(add(5, 3)); // Output: 8 console.log(subtract(10, 4)); // Output: 6 logMessage('Hello, world!'); // Output: Hello, world! console.log(square(4)); // Output: 16 console.log(multiply(5, 3)); // Output: 15 console.log(divide(10, 2)); // Output: 5
index.html
<!-- index.html --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>JavaScript Modules Example</title> </head> <body> <script type="module" src="main.js"></script> </body> </html>
Here’s an explanation of each part:
ways to Import module :explanation with code example
In JavaScript, there are different ways to import modules depending on the type of exports in the module. Let’s go through the ways to import modules with code examples.
When a module exports values using named exports, you can import those specific values by their names.
Example: math.js (Exporting Named Values)
// math.js export const add = (a, b) => a + b; export const subtract = (a, b) => a - b;
Example: main.js (Importing Named Values)
// main.js import { add, subtract } from './math.js'; console.log(add(5, 3)); // Output: 8 console.log(subtract(10, 4)); // Output: 6
2. Default Export:
When a module has a default export, you can import it using any name you choose.
Example: logger.js (Exporting a Default Value)
// logger.js const logMessage = (message) => console.log(message); export default logMessage;
Example: main.js (Importing a Default Value)
// main.js import logMessage from './logger.js'; logMessage('Hello, world!'); // Output: Hello, world!
3. Mixed Named and Default Exports:
When a module exports a mix of named and default values, you can import them accordingly.
Example: utils.js (Exporting Named and Default Values)
// utils.js export const multiply = (a, b) => a * b; export const divide = (a, b) => a / b; // Default export const square = (x) => x * x; export default square;
Example: main.js (Importing Named and Default Values)
// main.js import square, { multiply, divide } from './utils.js'; console.log(square(4)); // Output: 16 console.log(multiply(5, 3)); // Output: 15 console.log(divide(10, 2)); // Output: 5
4. Importing Everything:
You can import all exports from a module as properties of a single object using the * wildcard.
Example: math.js (Exporting Named Values)
// math.js export const add = (a, b) => a + b; export const subtract = (a, b) => a - b;
Example: main.js (Importing All Values)
// main.js import * as math from './math.js'; console.log(math.add(5, 3)); // Output: 8 console.log(math.subtract(10, 4)); // Output: 6
Choose the appropriate import method based on the structure of the module you are working with. Import statements should be placed at the top of your JavaScript file before you use the imported values.
complete code example in html with explanation
math.js
// math.js export const add = (a, b) => a + b; export const subtract = (a, b) => a - b;
logger.js
// logger.js const logMessage = (message) => console.log(message); export default logMessage;
utils.js
// utils.js export const multiply = (a, b) => a * b; export const divide = (a, b) => a / b; // Default export const square = (x) => x * x; export default square;
main.js
// main.js import { add, subtract } from './math.js'; import logMessage from './logger.js'; import square, { multiply, divide } from './utils.js'; console.log(add(5, 3)); // Output: 8 console.log(subtract(10, 4)); // Output: 6 logMessage('Hello, world!'); // Output: Hello, world! console.log(square(4)); // Output: 16 console.log(multiply(5, 3)); // Output: 15 console.log(divide(10, 2)); // Output: 5
index.html
<!-- index.html --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>JavaScript Modules Example</title> </head> <body> <h1>JavaScript Modules Example</h1> <script type="module" src="main.js"></script> </body> </html>
Explanation:
addition.js
// addition.js export const add = (a, b) => a + b;
subtraction.js
// subtraction.js export const subtract = (a, b) => a - b;
multiplication.js
// multiplication.js export const multiply = (a, b) => a * b;
division.js
// division.js export const divide = (a, b) => (b !== 0 ? a / b : 'Cannot divide by zero');
calculator.js
// calculator.js import { add } from './addition.js'; import { subtract } from './subtraction.js'; import { multiply } from './multiplication.js'; import { divide } from './division.js'; export const calculate = (operation, a, b) => { switch (operation) { case 'add': return add(a, b); case 'subtract': return subtract(a, b); case 'multiply': return multiply(a, b); case 'divide': return divide(a, b); default: return 'Invalid operation'; } };
main.js
// main.js import { calculate } from './calculator.js'; // Examples console.log(calculate('add', 5, 3)); // Output: 8 console.log(calculate('subtract', 10, 4)); // Output: 6 console.log(calculate('multiply', 5, 3)); // Output: 15 console.log(calculate('divide', 10, 2)); // Output: 5 console.log(calculate('divide', 5, 0)); // Output: Cannot divide by zero console.log(calculate('power', 2, 3)); // Output: Invalid operation
index.html
<!-- index.html --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Simple Calculator</title> </head> <body> <h1>Simple Calculator</h1> <script type="module" src="main.js"></script> </body> </html>
Explanation:
This simple calculator application showcases the use of JavaScript modules to organize and structure code.
a. To add styling to HTML
b. To organize and structure code
c. To create animations
d. To handle input
a. export default
b. export const functionName
c. export functionName
d. module.export = functionName
a. import { functionName } from ‘module’
b. import functionName from ‘module’
c. import * as moduleName from ‘module’
d. import ‘module’
a. export default
b. export
c. default export
d. module.export
a. To define the module type
b. To include external stylesheets
c. To specify the script type as JavaScript
d. To import external modules
a. import * from ‘module’
b. import { * } from ‘module’
c. import * as objectName from ‘module’
d. import { objectName } from ‘module’
a. export default, { namedValue }
b. export { namedValue, default }
c. export { namedValue, as default }
d. export { namedValue } from ‘module’
a. To import values from another module
b. To define a variable
c. To export values from the current module
d. To create a function
a. import
b. require
c. module.import
d. module.require
a. export value;
b. module.export = value;
c. export default value;
d. module.export default value;
a. The code runs without errors
b. The browser displays an error message
c. The import statement is ignored
d. The script stops executing
a. .jsm
b. .es6
c. .mod
d. .mjs
a. CommonJS
b. AMD
c. UMD
d. ES6 Modules
a. To import all values from a module as properties of a single object
b. To import a single value from a module
c. To import only named exports from a module
d. To import the default export from a module
a. Open the HTML file in a browser
b. Use the node command in the terminal
c. Execute it in a code editor
d. Run it as a server-side application
1-: b. To organize and structure code
2-: b. export const functionName
3-: b. import functionName from ‘module’
4-: a. export default
5-: a. To define the module type
6-: c. import * as objectName from ‘module’
7-: a. export default, { namedValue }
8-: c. To export values from the current module
9-: a. import
10-: b. module.export = value;
11-: b. The browser displays an error message
12-: d. .mjs
13-: d. ES6 Modules
14-: a. To import all values from a module as properties of a single object
15-: a. Open the HTML file in a browser