I'm trying to achieve TypeScript code sharing in a create-react-app in non-eject mode, but I'm running into the infamous restriction that imports outside of src
are not allowed:
You attempted to import ../../common/src/lib.ts which falls outside of the project src/ directory. [...]
For the non-TypeScript case this has been asked & answered here, but I can't get any of the solutions to work with TypeScript. Specifically the issues with the proposed solutions are:
Setting
baseDir
ints-config.json
: Here create-react-app complains about: Your project'sbaseUrl
can only be set tosrc
ornode_modules
. Create React App does not support other values at this time.Approaches based on react-app-rewired: More promising. Disabling the
ModuleScopePlugin
gets me past the "attempted import outside src" error, but the problem now is that the loader of typescript files doesn't play along:I have verified that the
.ts
itself is fine: Copying to./src
and importing it from there works fine.I have also added
../../common/src
folder to theincludes
list ints-config.json
.My guess is that somehow the webpack loader configuration has a rule that prevents the TypeScript loader to transpile files that don't match its expected path patterns. How can this be fixed using react-app-rewired?
Symlinking sources doesn't work either -- again with the same problem. Probably because webpack internally resolves the symlinks and sees the file in a path where the normal loader rules don't apply.
Eject based solutions: I'd like not to eject for now, but I tried and I'm basically running into the same problem again.
I've also found other questions that sounded related but didn't answer the problem:
- Create React App + Typescript In monorepo code sharing: Sounds basically like the same question, but it is not, because it is asking for the case of an ejected React app.
- Sharing code between projects using TypeScript and webpack: Also addresses the code sharing problem, but not create-react-app specific, and I don't know if the solution can be transferred to create-react-app, because it requires manual webpack config control.
Re-using TypeScript typings in a mono repo seems to be a fairly reasonable pattern. Am I missing something or why is the create-react-app making this so difficult?
To reproduce: My code is basically 100% what you get from
npx create-react-app my-app --template typescript
with one import to external added.