How to import two classes by the same name in javascript/es6?

Ecmascript 6

Ecmascript 6 Problem Overview


I have these two import statements in file:

import Data from 'component/Data.js';
import Data from 'actions/Data.js';

Both files contain a class named Data.

How can I specify which is which? How can I avoid name clash?

Ecmascript 6 Solutions


Solution 1 - Ecmascript 6

Presumably component/Data and actions/Data both have default exports rather than named exports? Like this:

export default class Data {}

If that's the case, then the importer can call the variables whatever they like:

import Data1 from 'component/Data.js';
import Data2 from 'actions/Data.js';

If they are named exports:

export class Data {}

Then you need to use braces along with as to specify the source and target names:

import { Data as Data1 } from 'component/Data.js';
import { Data as Data2 } from 'actions/Data.js';

Solution 2 - Ecmascript 6

EDITED: As per RGraham answer, updating my answer:

Can't you import it like this:

import {Data as D1} from 'component/Data.js';
import {Data as D2} from 'actions/Data.js';

Then use it as you require:

D1.{}
D2.{}

referenced from: https://github.com/lukehoban/es6features/blob/master/README.md/#user-content-modules

Solution 3 - Ecmascript 6

There are two alternatives:

import {MyClass as c1} from ......
import {MyClass as c2} from ......

or second alternative:

import MyClass from .......
import {MyClass as c2} from ......

You can use first line but in some cases, you may get stuck using the first line.Then use the second line.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnthony KongView Question on Stackoverflow
Solution 1 - Ecmascript 6CodingIntrigueView Answer on Stackoverflow
Solution 2 - Ecmascript 6SavaratkarView Answer on Stackoverflow
Solution 3 - Ecmascript 6Apurba AView Answer on Stackoverflow