Search code examples
reactjsdirectory-structure

How to structure a React ES6 application to promote reuse of common code


We have a react es6 application being transpiled with babel. It has the following file structure:

- Root - common - common-component - common-component.spec.js - project1 - .babelrc - .jest.json - package.json - node_modules - src - component - component.js - component.spec.js - project2 - .babelrc - ...

I want to build, test and run project1. This build should include the source and tests from both common and project1 and ignore the content of project2.

I currently see babel walks up the directory tree looking for .babelrc and node_modules etc. When running under the context of project1, this obviously doesn't find them and a transpilation error occurs.

Is there a way to include files from common when issuing an npm run test from within the project1 directory?

Or, alternatively, should common, project1 and project2 be considered independent projects with their own package.json, .babelrc, node_modules etc. If this is the case how would I be able to run tests from common when building project1 or project2?

I feel like I'm missing something obvious in terms of code reuse with multiple projects.

Thanks in advance.


Solution

  • In case anyone else comes across this.

    We found 2 solutions to achieve the scenario outlined.

    1. Use git submodules to include the common code repo as a subfolder of project1 and/or project2.

    2. Build an npm package for common code and pull that down into project1 and/or project2.

    We decided to go with option 2, and run a separate project through our build pipeline that tested common components in isolation from any projects.