DEV Community

Cover image for Import and Rename Named Exports
chantastic
chantastic

Posted on • Originally published at chan.dev on

Import and Rename Named Exports

JavaScript Modules have a syntax for remaning named exports, at import.

import { exportedName as localName } from "";
Enter fullscreen mode Exit fullscreen mode

I think about this as "given name" and "nickname". Michael Chan is the name my creators gave me but — on this site — I go by chantastic.

import { michaelChan as chantastic } from "./michael-chan.mjs";
Enter fullscreen mode Exit fullscreen mode

This is one of two tools we have for avoiding naming collisions between modules.

Rename named exports to avoid a collision #

In my last post — Import Named Exports — we imported two functions from the string-utils module: hype and chant.

import { hype, chant } from "./string-utils.mjs";
Enter fullscreen mode Exit fullscreen mode

What if the modules we're working in already has a hype function? Are we stuck stuck? Do we have to refactor our code to consider the new module?

Nope!

We use the as keyword to rename named exports locally.

- import { hype, chant } from "./string-utils.mjs";+ import {+ hype as hypeText,+ chant+ } from "./string-utils.mjs";
Enter fullscreen mode Exit fullscreen mode

With as, we have full control of the module we're working in.

We can assign named exports to any free, local identifier.

My take #

The as keyword gives us a way to avoid naming collisions, or use a name that's more contextually accurate. This is great for working with modules in a codebase and the larger npm ecosystem.

However, I find this to be a less ideal form collision avoidance than importing all of a module's contents into a single variable.

But we'll cover that in a future post 😅.

Go pro #

This is part of a course I'm build on modules at lunch.dev.

When live, members get access to this and other courses on React.

Join lunch.dev for videos

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay