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: testImport is exported as test in sample.js
  • Import renaming: tellTime is imported as showTime in script.js
  • The renamed functions are used with their new names in the importing module

Output

Renaming imports and exports in JavaScript CLICK HERE Click on the above button to execute the imported functions Module testImport has been imported Current time: Mon Nov 20 2023 14:30:45 GMT+0000 (UTC)

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.

Updated on: 2026-03-15T23:18:59+05:30

259 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements