Search code examples
reactjsbabeljsreact-chartjs

Import only specific components in react


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.


Solution

  • 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