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
Renaming imports and exports in JavaScript
JavaScript ES6 modules allow you to rename imports and exports using the as keyword. This is useful for avoiding naming conflicts, improving code readability, or providing more descriptive names for functions and variables.
Note ? You need to run a localhost server to run this example due to ES6 module requirements.
Syntax
For renaming exports:
export { originalName as newName };
For renaming imports:
import { originalName as newName } from './module.js';
Example
Let's create a complete example with three files demonstrating both import and export renaming:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Renaming Imports and Exports</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
font-size: 18px;
font-weight: 500;
color: rebeccapurple;
margin: 20px 0;
}
</style>
</head>
<body>
<h1>Renaming imports and exports in JavaScript</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to execute the imported functions</h3>
<script src="script.js" type="module"></script>
</body>
</html>
script.js
import {test, tellTime as showTime} from "./sample.js";
let resultEle = document.querySelector('.result');
document.querySelector('.Btn').addEventListener('click', () => {
resultEle.innerHTML += test();
resultEle.innerHTML += showTime();
});
sample.js
function testImport() {
return "Module testImport has been imported<br>";
}
function tellTime() {
return "Current time: " + new Date() + "<br>";
}
export { testImport as test, tellTime };
How It Works
In this example:
-
Export renaming:
testImportis exported astestin sample.js -
Import renaming:
tellTimeis imported asshowTimein script.js - The renamed functions are used with their new names in the importing module
Output
Key Benefits
- Avoiding conflicts: Rename imports when names conflict with existing variables
- Better readability: Use more descriptive names in your code context
- API consistency: Maintain consistent naming conventions across modules
Conclusion
The as keyword in ES6 modules provides flexibility for renaming both imports and exports. This feature helps maintain clean, readable code while avoiding naming conflicts between modules.
Advertisements
