2

I have two different and separated web apps, both developed with React. The two apps should share some React components. I would like to have a general project structure as follow:

.
├── cms-client
├── my-app
└── shared

where:

  • cms-client and my-app are two standard React apps;
  • shared is a folder containing the shared components, that should be used by the other two apps.

I tried to add a symbolic link inside the two src folders of the apps, like:

ln -s ../../shared/ .

executed inside the src folder of each app. In this case, when I try to use a shared component, the compilation failed:

../shared/Example.js
SyntaxError: /my-long-project-path/React/shared/Example.js: Unexpected token (6:12)

  4 |     render() {
  5 |         return (
> 6 |             <div>
    |             ^
  7 |                 <p>I am an Example of Shared Component</p>
  8 |             </div>
  9 |         )

like it is compiled as a standard js file, and not a React jsx file.

So, I'm trying a different approach, using a custom configuration of the jsconfig.json file. Now, my idea is to inject somehow the shared folder, but it seems impossible.

I could write a Gulp script that watch the shared folder, and then copy the contents inside the shared folder of the two project, but this isn't an optimal solution and very error prone (from my IDE, I need to pay attention on which of the three shared folder I'm editing). Moreover, the standard react-scripts is already watching the src folder for any changes. So, if someone has a better solution, it will be great!!!

LucaRoverelli
  • 1,116
  • 1
  • 9
  • 15
  • If you keep the shared files all in a separate git repo, you could always follow [this stuff](https://stackoverflow.com/a/17509764/8230810) and treat them like third-party components – James Whiteley Oct 10 '19 at 09:57
  • How does the build process generally determine whether a file should be processed as a normal JS file or as a React file? What are you using to transpile React files? My first impression is that you simply need to configure your build tool correctly, but you don’t provide any information about it. – Felix Kling Oct 10 '19 at 09:58
  • @FelixKling I'm using the standard `react-scripts` command. Unfortunately, in the react documentation they just said that the files should be in the `src` folder. Maybe the `ln` trick is not enough for Babel or Webpack – LucaRoverelli Oct 10 '19 at 10:02

1 Answers1

1

Can you do npm link on your shared ?

This will compile, package, and copy to some location on you machine

Then on both cms-client and my-app do npm link shared

It will create symlink in node_modules point to the locally shared

sgennrw
  • 156
  • 8
  • This can be a nice solution! I was searching for something lighter, using `npm link` means that my `shared` folder became a complete `npm` module. – LucaRoverelli Oct 10 '19 at 12:31