Import same-named classes from different libraries

Import same-named classes from different libraries

2016, Oct 24    

The problem

Import same named classes from differenet modules

Use case

Someone was investigating the already existing solutions for bar graphs, so, at some point, he wanted to test in the same page two different bar chart components, let’s say from react-svg-chart and recharts libraries.

Talking about external libraries, he had to import what he needed from them, so, he ended up, among the rest, with the following two imports, too:

import { BarChart } from 'react-svg-chart';
import { BarChart, Bar, Brush, ReferenceLine, XAxis, YAxis, CartesianGrid, Tooltip, Legend } from 'recharts';

Apparently, the intention was to render both of those, like:

<BarChart
    width=800
    height=600
    ...
/>

But what he didn’t think about was that the compiler wouldn’t be able to identify what kind of BarChart he was referring to, every time: the one from recharts or the other from ?!

Alias to the rescue

Although he is totally new to the js world, the import alias worked like a charm!

import { BarChart } from 'react-svg-chart';
import { BarChart as RCBarChart, Bar, Brush, ReferenceLine, XAxis, YAxis, CartesianGrid, Tooltip, Legend } from 'recharts';

That is, then he could test both components in one page/render, without receiving any complaints:

<BarChart
    width=800
    height=600
    ...
/>
<RCBarChart
    width=800
    height=600
    ...
/>

Closing Quote

Even the easiest things in life reveal you some kind of magic when you discover them alone.