Questions about monorepos with both React apps and component libraries in them
In our company, we have a bunch of React apps (all created with create-react-app). We want to share more code between them.
Our idea is to use a monorepo, with the apps under an apps/ subdirectory, and several libraries (each with a different set of dependencies on external libs) under libs/ .
We wouldn't need to put the libraries on npm, as we want to just refer to the code in libs/ from within the apps (and never import things from apps in other apps).
We use Typescript (not negotiable) and CSS modules / sometimes Emotion (but we would be open to other CSS solutions).
I have now spent a while figuring out how to achieve this, and holy crap is it complicated. I just can't do it.
-
There are guides out there, but Create-React-App ignores the TS "paths" config option. That can be changed using tools like craco, but craco doesn't support CRA 5 yet.
-
Even if I got it somewhat working after ejecting, I wasn't able to settle on a config that works for both Webpack and the TS language server that editors use. Especially not CSS modules.
-
Every other solution I see seems to use monorepos only for libraries, not apps. But then we are back to a workflow where we constantly need to make commits and releases of libraries before we can use them in apps, and version problems, so we won't get many of the advantages of a monorepo.
-
I haven't even started looking at Storybook yet, but we like that too.
Is what we want so unusual? Does anyone know a public repo that has what I want working? Should I just give up and only use a monorepo for libraries? We aren't married to create-react-app, if we have to use something else we will.
Posted Jun 29, 2022, 11:15 AM UTC · edited
Here are some tips for TS:
- Use NPM/Yarn/PNPM Workspaces
- Each library in lib/* has its own package.json, tsconfig.json, .eslintrc.js, ...etc. For ease of use - make a shared package where you keep common config and extend it
- Each library and app is stand-alone, it's built on its own, and it has a 'main' (or files) entry in package.json. In other words - imagine you were going to publish the package and it would get used in an entirely different project. You don't use ts paths and you have very little config at the root level (most likely for prettier or jest). No root-level tsconfig.json, no root level eslint
- In the apps simply put your library package names in the dependencies, as you would normally add an npm dependency. NPM/Yarn/PNPM workspaces will resolve it to your version in libs/*, it doesn't have to be published
- Use a build management tool for mono repo to make your life easier, (or just something like yarn workspaces foreach) - it will run your scripts in all libraries. For example if you have a 'dev' script in all package.json's that runs tsc -w you can run it for all libraries at once. I've used Turborepo and NX for that
I can't say anything for CSS modules though.