Search code examples
javascriptreactjsnpmreact-componentpreact

What is the best way to create component library for both React and Preact?


I'm currently working on a project which involved both React and Preact. I came across to this where I need to use same component for React and Preact.

Is it a good idea to put the component into npm library package. What are the possible way to create component library for both React and Preact? Looking forward to hear your ideas and discussions.

The code might look like as the following:

React Project: Home.js

import React from 'react'
import Fancy from 'fancy-component/react' // My <Fancy /> component library

class Home extends React.Component {
  render() {
    return (
      <div>
        {/* Other parts of the code run here*/}
        <Fancy text='🦄' />
      </div>
    )
  }
}

export default Home

Preact Project: AnswerPage.js

import { h, Component } from 'preact'
import Fancy from 'fancy-component/preact' // My <Fancy /> component library

class AnswerPage extends Component {
  render() {
    return (
      // Other Preact codes run here again
      <Fancy text='🚀 again' />
    )
  }
}

export default AnswerPage

Component library: fancy-component

const Fancy = ({ text = '' }) => (
  <div>
    <span>{`This is so Fancy ✨ ${text}`}</span>
  </div>
)
export default Fancy

Solution

  • We did this very thing recently, and because we could not find much information regarding this online it involved quite a bit of trial and error. This is what we ended up with:

    Folder Structure:

    /apps
      /mobile
      /desktop
    /shared
      /components
    

    With preact 10, preact-compat is built in so you don't have to worry having separate components - just use React as normal for the components in your shared folder and preact will automatically alias the imports correctly.

    As far as aliasing goes, we added this into our preact.config.js so that we can import the components like @components/Date from the app directory

    config.resolve.alias['@components'] = path.resolve(__dirname, '../../shared/components')
    

    For the React app, the only way that I could make that work was to add the aliasing in the babel.config.js like so:

    ['module-resolver', {
      alias: {
        '@components': '../../shared/components'
      }
    }]
    

    I hope that this helps someone else that might be stuck on this!