Vincent
Vincent

Reputation: 5425

How do I get create-react-app to compile code outside /src?

I have a folder which contains two projects, /frontend and /backend, where /frontend is a project using create-react-app-typescript.

Now, I want to share some code between both projects (most notably: type definitions for the API responses). These are currently located in /lib.

However, when I try to import code from within /lib inside a React component, create-react-app tells me that

Module not found: You attempted to import ../../../lib/endpoints/example which falls outside of the project src/ directory. Relative imports outside of src/ are not supported. You can either move it inside src/, or add a symlink to it from project's node_modules/.

I'd prefer not to move shared code inside /frontend/src. However, having it located in node_modules appears to result in the TypeScript code that's in there not being compiled. Since I'm trying to preserve hot reloading in development, compiling it before starting it wouldn't solve that.

Is there a way to configure create-react-app to also compile a specific directory, such as /frontend/node_modules/lib?

Upvotes: 4

Views: 4002

Answers (2)

Lukas Bach
Lukas Bach

Reputation: 3909

What you are trying to achieve is creating a monorepo. There are tools made specifically for that, notably Lerna. Lerna can be used to create multiple NPM-packages within one repository, and softlink them within each other so that e.g. one frontend-package can access a common-package in a different directory (but within the same repository) by creating a softlink from the node_modules directory of the frontend-package.

Upvotes: 0

Arnab
Arnab

Reputation: 154

I structured my project like this

enter image description here

Then executed following commands to link lib folder in frontend and backend sub-folders

cd frontend
npm link ../lib
cd ../backend
npm link ../lib

Now any source code I add inside lib, are immediately available in backend and frontend

Upvotes: 2

Related Questions