Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ecmascript-6

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?

like image 202
Anthony Kong Avatar asked Jan 11 '16 05:01

Anthony Kong


People also ask

Can we import class in JavaScript?

The import/export syntax is called JavaScript modules. In order to be able to import a class from a different file, it has to be exported using a named or a default export. The example above uses a named export and a named import.

How many parts are there in an ES6 Module 2?

The ES6 module standard has two parts: Declarative syntax (for importing and exporting) Programmatic loader API: to configure how modules are loaded and to conditionally load modules.

What is import and export in ES6?

With the help of ES6, we can create modules in JavaScript. In a module, there can be classes, functions, variables, and objects as well. To make all these available in another file, we can use export and import. The export and import are the keywords used for exporting and importing one or more members in a module.

Can we export multiple classes from a component in angular?

You can only have one default export.


1 Answers

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'; 
like image 107
CodingIntrigue Avatar answered Oct 02 '22 11:10

CodingIntrigue