Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to import and export a module/library in JavaScript?
Note ? To run this example you will need to run a localhost server.
JavaScript modules allow you to break code into separate files and share functionality between them using export and import statements. This promotes code reusability and better organization.
Example
INDEX.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
font-size: 18px;
font-weight: 500;
}
</style>
</head>
<body>
<h1>JavaScript Importing and Exporting Modules</h1>
<button class="Btn">IMPORT</button>
<div class="result"></div>
<h3>Click on the above button to import module</h3>
<script src="script.js" type="module"></script>
</body>
</html>
script.js
import test from './sample.js';
document.querySelector('.Btn').addEventListener('click', () => {
test();
});
sample.js
let resultEle = document.querySelector(".result");
export default function testImport() {
resultEle.innerHTML = 'Module testImport has been imported';
}
Export Types
Default Export
Export a single main function or class from a module:
// math.js
export default function add(a, b) {
return a + b;
}
// main.js
import add from './math.js';
console.log(add(5, 3)); // 8
Named Export
Export multiple functions or variables:
// utils.js
export function multiply(a, b) {
return a * b;
}
export const PI = 3.14159;
// main.js
import { multiply, PI } from './utils.js';
console.log(multiply(4, 5)); // 20
console.log(PI); // 3.14159
Import Variations
| Import Type | Syntax | Use Case |
|---|---|---|
| Default Import | import name from './module.js' |
Single main export |
| Named Import | import { func } from './module.js' |
Specific functions/variables |
| Namespace Import | import * as utils from './module.js' |
All exports as object |
| Rename Import | import { func as newName } from './module.js' |
Avoid naming conflicts |
Output
The above code will produce the following output ?
On clicking the 'IMPORT' button ?
Key Points
- Use
type="module"attribute in script tags - Modules must be served from a web server (not file://)
- Default exports can be imported with any name
- Named exports must use exact names in curly braces
Conclusion
JavaScript modules provide a clean way to organize code across files. Use default exports for main functionality and named exports for utilities. Always serve modules from a web server for proper functionality.
Advertisements
