DailyJS
Published in

DailyJS

Using Import aliases in JavaScript

Renaming module Imports like a Pro, now with added use-case!

Photo by Finan Akbar / Unsplash

The basics again (in brief)

  1. by using export on different functions or objects.
  2. by using export default on a single function or object.
  1. Import all exports into current module scope — import * from "my-module.js"
  2. Import particular named exports — import { func1, obj2 } from "my-module.js"
  3. Import the default export — import func from "my-module.js"
  4. Run a module’s global code but not import anything — import "my-module.js"
  5. Dynamic importing a module — import("my-module.js").then((module) => { //...do something })

Why is this important?

Failed to compile.
/Users/gregbyrne/Project/One/src/pages/index.js
SyntaxError: /Users/gregbyrne/Project/One/src/pages/index.js: Identifier 'Card' has already been declared (6:9)
4 | import { Button } from '../components/button'
5 | import { Card } from '../components/card'
> 6 | import { Card } from 'react-native-elements'
// Card.js in project/src/components/card
import { Card } from "cool-component-library"
const Card = () => (
// abstraction over cool-component-library card
// suitable for your project needs
)
const ListCard = () => (
// like above
)
export { Card, ListCard }// ---// Index.js in project/src/pagesimport { Card } from '.../components/card'// ... index page code

Differentiating your imports

TL;DR

// my-module.js// ... code ..export { Something1, Something2}
import { Something1 as MySomething } from "my-module.js"
// my-module.js// ... code ..export default Something
import MySomething from "my-module.js"
// Card.js in project/src/components/card
import { Card as CoolCard } from "cool-component-library"
const Card = () => (
// abstraction over cool-component-library card
// suitable for your project needs
)
const ListCard = () => (
// like above
)
export { Card, ListCard }
// Button.js in project/src/components/buttonimport CoolButton from "cool-component-library-button"const MyButton = () => (
// code
)
export default MyButton// ---// Index.js in project/src/pagesimport Button from '.../components/button/Button.js'// ... index page code

--

--

JavaScript news and opinion.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Greg Byrne

Engineer of Software. Breaking life’s hurdles with peregrine speed and a manatee’s grace.