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;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With