A JavaScript module is a file that contains reusable code. Each module has its own scope, which means that variables, functions, and classes defined in one module are not accessible from other modules by default. This isolation helps in preventing naming conflicts and makes the code more modular.
The two main keywords used in JavaScript modules are export
and import
.
// math.js
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
// greeting.js
const greeting = () => 'Hello, World!';
export default greeting;
// main.js
import { add, subtract } from './math.js';
console.log(add(5, 3)); // Output: 8
console.log(subtract(5, 3)); // Output: 2
// main.js
import greeting from './greeting.js';
console.log(greeting()); // Output: Hello, World!
To use JavaScript modules in the browser, you need to set the type
attribute of the <script>
tag to module
.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<script type="module">
import { add } from './math.js';
console.log(add(2, 3));
</script>
</body>
</html>
In Node.js, you can use the .mjs
file extension for module files. Starting from Node.js v13.2.0, you can also use the "type": "module"
in your package.json
file to use the .js
extension for modules.
// main.mjs
import { add } from './math.mjs';
console.log(add(4, 6));
Group related functions, classes, and variables into a single module. For example, if you have a set of functions related to user authentication, you can create an auth.js
module.
// auth.js
export const login = (username, password) => {
// Login logic here
};
export const logout = () => {
// Logout logic here
};
Since modules have their own scope, avoid using global variables as much as possible. Instead, use exports and imports to share data between modules.
Use descriptive names for your modules, exports, and imports. This makes the code more readable and easier to understand. For example, instead of naming a module utils.js
, you can name it stringUtils.js
if it contains functions related to string manipulation.
Each module should have a single responsibility. If a module starts to grow too large, consider splitting it into smaller, more focused modules.
When importing modules, handle errors gracefully. For example, if a module fails to load, display a meaningful error message to the user.
import('./myModule.js')
.then((module) => {
// Use the module
})
.catch((error) => {
console.error('Error loading module:', error);
});
JavaScript modules are a powerful feature that helps in organizing and managing code effectively. By understanding the fundamental concepts of exports and imports, and following common and best practices, you can write more modular, maintainable, and reusable code. Whether you are working on a small web project or a large-scale application, JavaScript modules are an essential tool in your development toolkit.