How to use common component between Create React APP(CRA) and Gatsby where component consists of <Link> tag?

Viewed 135

I have a monorepo where the applications are built with CRA and GATSBYJS. Few components are shared between these applications like dropdowns, navbar, footer etc.,

Structure of Monorepo:

MONOREPO
|
|
---> COMMON
|    |
|    |
|    ---> NAVBAR
|
|
---> CRA
|
|
---> GATSBY
|
|
babel.config.js

Navbar component has a Link element. But, the Link element for CRA is different from GATSBYJS. The way the Navbar component written was:

/COMMON/NAVBAR

class Navbar extends Component{

render(){
   const {appType} = this.props;

   let Link;
   if(appType === 'CRA'){
      ({Link} = React.lazy(() => import('react-router-hash-link'))
   } else if(appType === 'GATSBY){
      Link = React.lazy(() => import('../gatsby/LinkComponent'))
   }
}
}

/GATSBY/LinkComponent

import {Link} from 'gatsby';

class LinkComponent extends Component{

render(){

   const {to} = this.props;

   return(
     <Link to={to} />
   )
}
}

When compiling CRA application, it is trying to parse GATSBY file and throwing the following error:

enter image description here

and here is my babel.config.js for monorepo:

module.exports = {
  env: {
    development: {
      plugins: ['transform-es2015-modules-commonjs']
    },
    test: {
      plugins: [
        'transform-es2015-modules-commonjs',
        '@babel/plugin-proposal-class-properties',
        'dynamic-import-node'
      ],
      presets: ['@babel/preset-react']
    },
  }
};

Not sure, which loader is required here!

1 Answers

It was minor trick that the module parser expecting. All I had to do was

From

class Navbar extends Component{

render(){
   const {appType} = this.props;

   let Link;
   if(appType === 'CRA'){
      ({Link} = React.lazy(() => import('react-router-hash-link'))
   } else if(appType === 'GATSBY){
      Link = React.lazy(() => import('../gatsby/LinkComponent'))
   }
}
}

To

class Navbar extends Component{

render(){
   const {appType} = this.props;

   let Link;
   if(appType === 'CRA'){
      Link = React.lazy(() => import('../cra/LinkComponent'))
   } else if(appType === 'GATSBY){
      Link = React.lazy(() => import('../gatsby/LinkComponent'))
   }
}
}
Related