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
Explain import "as" and Export "as" constructs in JavaScript.
Import as and export as constructs allow you to rename modules during import/export operations, providing flexibility and avoiding naming conflicts in JavaScript.
What is Import "as"?
The import as syntax allows you to import a named export under a different name in the importing module. This is useful when you want to avoid naming conflicts or use more descriptive names.
What is Export "as"?
The export as syntax allows you to export a function or variable under a different name than its original declaration. This gives you control over how your module's API is exposed.
Syntax
// Import with alias
import { originalName as newName } from './module.js';
// Export with alias
export { originalName as newName };
Example: Export "as" in sample.js
// sample.js
function testImport() {
return "Module testImport has been imported ";
}
function tellTime() {
return new Date().toLocaleString();
}
// Export with alias - testImport exported as 'test'
export { testImport as test, tellTime };
Example: Import "as" in main script
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Import/Export As Example</title>
</head>
<body>
<h1>Import as and Export as in JavaScript</h1>
<div id="result"></div>
<button id="btn">CLICK HERE</button>
<script type="module">
// Import with alias - tellTime imported as 'showTime'
// import {test, tellTime as showTime} from "./sample.js";
// Simulating the module for demo purposes
function test() {
return "Module testImport has been imported<br>";
}
function showTime() {
return new Date().toLocaleString() + "<br>";
}
let resultEle = document.getElementById('result');
document.getElementById('btn').addEventListener('click', () => {
resultEle.innerHTML += test();
resultEle.innerHTML += showTime();
});
</script>
</body>
</html>
Key Benefits
| Feature | Import "as" | Export "as" |
|---|---|---|
| Avoid naming conflicts | ? | ? |
| Rename for clarity | ? | ? |
| Control API naming | - | ? |
Common Use Cases
- Avoiding conflicts: When importing modules with similar function names
- Clarity: Renaming imported functions to be more descriptive in context
- API design: Exposing internal functions under different public names
Conclusion
Import "as" and export "as" constructs provide essential flexibility in JavaScript modules. Use them to avoid naming conflicts and create cleaner, more maintainable code.
