1

I'm working on a web project with react.
How can I import only 3 Components from a library.
I have used:

import Line, Bar, Doughnut from 'react-chartjs-2';

gives an error.

import Line from 'react-chartjs-2';
import Bar from 'react-chartjs-2';
import Doughnut from 'react-chartjs-2';

makes all Line, Bar and Doughnut elements act as Doughnut elements.

Using

import {Line, Bar, Doughnut} from 'react-chartjs-2';

loads the whole library, which is something I don't want.

NOTE: I use that import in multiple files.

Soviut
  • 88,194
  • 49
  • 192
  • 260
Rado
  • 155
  • 12
  • 1
    `import { Doughnut, Line, Bar } from 'react-chartjs-2'` try this one – The Reason Nov 28 '16 at 16:26
  • 1
    `import Line from 'react-chartjs-2/Line'; import Bar from 'react-chartjs-2/Bar'; import Doughnut from 'react-chartjs-2/Doughnut';` Could it work? (I didn't test it, just want to give it a try.) – Andre Lee Nov 28 '16 at 16:32
  • 1
    What do you mean whole lib? take a look at [git repo](https://github.com/gor181/react-chartjs-2). It should work as you want – The Reason Nov 28 '16 at 16:33
  • @TheReason [link](http://stackoverflow.com/a/34241128/3327294) – Rado Nov 28 '16 at 16:39
  • @AndreLee sadly that doesn't work, neither does `import Line from 'react-chartjs-2/components/line';` – Rado Nov 28 '16 at 16:54
  • @AndreLee No that doesn't work either, also replacing the '/' with '.' doesn't work – Rado Nov 28 '16 at 17:00

1 Answers1

2

It's about how the author building, packaging, exporting the components/modules/classes.

Take a look at the gulpfile.js and /lib of react-chartjs-2, you will see each class wasn't exported as a module (CommonJS), so you only can import the class Doughnut (or other classes) like this:

import { Doughnut } from 'react-chartjs-2'

unless you separate the code and rebuild them yourself.

If you are interested in why react-bootstrap can do that, check its webpack config, build tools, and code structure. And more we can get from:

  • file structure of react-chartjs-2's distribution

    file structure of react-chartjs-2's distribution

  • file structure of react-bootstrap's distribution

    file structure of react-bootstrap's distribution

Andre Lee
  • 1,180
  • 1
  • 11
  • 13