Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Exports From React Component Library

I'm trying to create a component library with multiple independent components. The end goal is to allow a user to do something like

import One from 'component-library' 
import Two from 'component-library'
<One/>
<Two/>

But I haven't been able to get anything to work.

My current layout is

src
 -index.tsx
 -components
  -one
  -two

An example of what my code looks like:

One.tsx

export default class One {
 ...
}

and then in my root index.tsx

import {default as One} from './components/one/One.tsx'
import {default as Two} from './components/two/Two.tsx'

export {
  one,
  two
}

This however doesn't work and returns undefined when attempting to import as demonstrated above. I was however able to get this to work only using one component and export {default} from './components/one/One.tsx' or just doing import One from '.components/one/One.Tsx' so I think my build process should be fine. In that case the component displayed correctly in my other project.

I've also tried modifying my structure and how I'm importing, for example using an index.tsx file in each of the components and exporting/importing from there. All of these have netted the same, returning undefined.

How can I export these correctly so that each one is discretely importable in a 3rd party project?

like image 227
newBieDev Avatar asked Oct 27 '25 09:10

newBieDev


1 Answers

Like Highlander, there can be only one default export from a given module. You can get the imports you want by importing distinct modules:

import One from 'component-library/One';
import Two from 'component-library/Two';

Or, you can use named exports and imports:

import { One, Two } from 'component-library';

But you can't have the same import return two different things based on the import name.

like image 184
Sean Vieira Avatar answered Oct 29 '25 22:10

Sean Vieira



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!