简体   繁体   中英

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.

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

You can use your shareable react project as a dependency for your other project, you can mention it in your package json dependencies, and import the things like how we do in any other node projects.

Mentioning a medium post here which I came across: https://medium.com/@Powderham/sharing-react-components-between-separate-projects-self-hosting-with-git-installing-with-yarn-npm-d3275b64239c

Let me know if this helps.

If you want to reuse a component, just copy and paste its *.jsx file into src/components . This is what you need to do to re-use a component.

admin and admin-client are in the same parent directory

This is irrelevant. They are two different applications.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM