最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

ecmascript 6 - ES6 Javascript Import same js file under multiple names - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question asked Oct 18, 2017 at 21:10 SehabSehab 2592 silver badges11 bronze badges 2
  • Why don't you just alias the first import? const Account = Contact – djfdev Commented Oct 18, 2017 at 21:30
  • 3 What is 'importing it multiple times' supposed to mean? A module can be imported wherever needed but it will be evaluated once. – Estus Flask Commented Oct 18, 2017 at 23:12
Add a ment  | 

2 Answers 2

Reset to default 7

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.

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'
发布评论

评论列表(0)

  1. 暂无评论