如何在 javascript/es6中导入同名的两个类?

我这里有两份导入报表:

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

两个文件都包含一个名为 Data的类。

如何指定哪个是哪个? 如何避免名称冲突?

59552 次浏览

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

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';

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.

if using

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

if this does work saying Data is not exported, you should clear the last path for example use

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

instead of

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