DEV Community

Stacky
Stacky

Posted on

Renaming Imports to Avoid Naming Collisions

Let's say you want to import and share a name with some other value that already exists in your program.

  • How to use the as keyword

For example, suppose you had access to two modules, greeterEspanol.js and greeterFrancais.js. Each exports a function called greet() :

/* inside greeterEspanol.js */

const greet = () => {
  console.log('hola');
}
export { greet };

/* inside greeterFrancais.js */
const greet = () => {
  console.log('bonjour');
}
export { greet };
Enter fullscreen mode Exit fullscreen mode

Now, let’s say you wanted to use each of these functions in a program, called main.js, that simulates a conversation between a spanish-speaker and a french-speaker.

import { greet } from 'greeterEspanol.js';
import { greet } from 'greeterFrancais.js';
//Error on line 2 identifier greet has
//already been defined on line 1.
Enter fullscreen mode Exit fullscreen mode

Thankfully, ES6 includes syntax for renaming imported resources by adding in the keyword as. It looks like this:

import { greet as greetEspanol } from 'greeterEspanol.js';
import { greet as greetFrancais } from 'greeterFrancais.js';

greetEspanol(); // Prints: hola
greetFrancais(); // Prints: bonjour
Enter fullscreen mode Exit fullscreen mode

Hopefully this knowledage comes to be useful when trying to manage your variable names in many different files.

Top comments (0)