Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import React component locally from a different create-react-app project?

I've created 2 React applications called client and admin-client, both using create-react-app.

In admin-client, I'd like to reuse some components that already exist in client in order to avoid code duplication.

For example, I have a Header.jsx file inside client/src/components/ directory which I want to reuse in admin-client, which looks like this:

import React from 'react';

function Header() {
    return (
        <header>
            <h2>Hello World!!</h2>
        </header>
    );
}

export default Header;

Here's what I've tried (and failed):

I've created an .env file inside admin-client project directory as follows:

NODE_PATH='./../'

(admin and admin-client are in the same parent directory)

Then inside admin-client/src/App.jsx, I try to import Header.jsx as follows:

import React from 'react';
import {Header} from 'client/src/components/Header.jsx';

function App() {
    return (
        <div>
            <Header />
        </div>
    );
}

export default App;

But I get the following error:

../client/src/components/Header.jsx 5:8
Module parse failed: Unexpected token (5:8)
You may need an appropriate loader to handle this file type.
| function Header() {
|     return (
>         <header>
|             <h2>Hello World!!</h2>

I prefer to find a solution that doesn't involve dealing with Babel and/or Webpack directly, because it's the reason that I'm using create-react-app in the first place.

like image 357
Utku Ufuk Avatar asked Jun 15 '19 10:06

Utku Ufuk


1 Answers

This is not a simple task if you do it manually, You'll probably end up on making a lot of changes on your repo just to make it in sync to your other apps. I suggest that you install a package called Bit which lets you share and sync UI components between your projects. You can read more about it here: https://docs.bit.dev/docs/installation.html

NPM

Install Bit using NPM:

npm install bit-bin --global

When installing Bit on windows, add the --no-optional flag: npm install bit-bin --global --no-optional

like image 121
user-9725874 Avatar answered Oct 01 '22 16:10

user-9725874