Sehab
Sehab

Reputation: 259

ES6 Javascript Import same js file under multiple names

I'm working with ES6 and I want to import the same file as 2 different names.

import Contact from './Grid'
import Account from './Grid'

Is there a way that I can have grid named by both contact and account without webpack importing it multiple times?

Upvotes: 3

Views: 6433

Answers (2)

loganfsmyth
loganfsmyth

Reputation: 161447

without webpack importing it multiple times?

Using two separate import statements will not execute the file multiple times. Once a file has been loaded once, its exported values are cached for use with later calls. Given that, the only reason to group it into one statement would be potential readability improvements. That said, to answer your question, you can do

import { 
  default as Contact,
  default as Account,
} from './Grid';

if you want. You could also potentially do

import Contact from './Grid'
const Account = Contact;

just note that it doesn't do quite the same thing in cases where there are circular dependencies in your modules.

Upvotes: 7

Lance Whatley
Lance Whatley

Reputation: 2455

If in your Grid file you are exporting your desired object/function/etc. as the default export (see below), you can use whatever name you want when importing. An example if Grid is a function would be:

//Grid file
export default function Grid() {
  // your Grid info
}

and

//import file
import Contact from './Grid'
import Account from './Grid'

Upvotes: 0

Related Questions