Course contentsShow
← JavaScript
Lesson 1415 of 2,72331. ModulesFree lesson

Renaming Imports with 'as'

Discover how to rename imported values using the 'as' keyword to avoid naming conflicts.

Renaming Imports with 'as'

You'll learn how to rename imported values using the as keyword to prevent naming conflicts and improve code clarity.

When importing from modules, you might encounter situations where imported names clash with existing variables in your code, or where the imported name isn't clear enough in your current context. The as keyword lets you create an alias for imported values, giving them a new name in your file.

The Core Problem

Imagine importing a format function from a date library and a format function from a currency library—you can't use both with the same name! Or perhaps an imported name like config is too generic and you want to be more specific.

Using 'as' to Rename

The syntax is straightforward:

// Import and rename a single export
import { format as formatDate } from './dateUtils.js';
import { format as formatCurrency } from './currencyUtils.js';

// Now you can use both without conflict
const dateString = formatDate(new Date());
const price = formatCurrency(19.99);

You can rename multiple imports in one statement:

import { 
  config as appConfig, 
  init as initialize 
} from './app.js';

appConfig.theme = 'dark';
initialize();

Think of It Like a Nickname

The as keyword is like introducing someone: "This is Robert, but we call him Bob." The module exports Robert, but in your code, you'll only use Bob. The original name doesn't exist in your scope.

Key Takeaway: Use the as keyword when importing to rename values and avoid naming conflicts or improve clarity: import { originalName as newName } from './module.js'.