-
To upgrade internal modules (in app source tree) to independent local private packages.
-
To share code between CRA-ts apps in a monorepo
-
While still be able to use IDE 'go to definition' to go to .ts source, instead of .d.ts
-
create-react-app (will eject to config webpack/jest to achieve #3 goal)
-
react-scripts-ts
-
yarn workspace
/ <-- project root
- packages/ <-- local packages root
- mymain/ <-- a local packages
- build/ <-- tsc outDir
- src/ <-- TypeScript source file
- index.ts <-- tsc import will use this if no build/
export * from './src';
- package.json
{
"name": "mymain", "version": "0.1.0", "license": "UNLICENSED", "private": true
"main": "build/index.js", <-- for webpack import
"types": "build/index.d.ts", <-- tsc import will use this if there's build/
}
- tsconfig.json
- webapp/ <-- a CRA-ts project, use mymain
- src/
- typescript.json
{
"extends": "../tsconfig-base.json",
"compilerOptions": {
"baseUrl": "../../packages", <-- allow import from 'mymain'
"outDir": "build/dist"
}
}
- package.json
- tsconfig-base.json <-- common tsconfig
- package.json
{
"name": "cra-ts-monorepo-example", "private": true,
"workspaces": [ "webapp", "packages/*" ]
}
-
Initial boilerplate from create-react-app-typescript in root/webapp commit.
-
Create yarn workspace commit.
-
Move CRA tsconfig.json to root to be shared with other local packages commit 1, commit 2.
-
Implement a trivial local packages
root/packages/mymaincommit. Run yarn now so it'll create symlink to mymain inroot/node_modules. Then we canimport from 'mymain'from anywhere. -
Make the CRA app use the new local packages commit. Now the CRA app will tsc compile correctly (because we have index.ts at mymain root). But when
yarn startit'll fail in browser because mymain isn't built. To fix this we can tsc in mymain to build the package and the app will run successfully. However, when wego to definitionto a symbol in mymain, it'll goto a .d.ts. -
To achieve goal #3, we configure tsconfig.json
baseUrlto directly reference local packages. Since webpack won't bundle code outsidewebapp/src, and jest won't find the packages, we have to eject to configure them. commit -
Simple webpack config hack to allow it to bundle code outside
webpack/src. This to achieve goal #3. commit. Don't forget to deletebuildin local packages, because otherwise everyone will usebuild/index.*(per NPM spec) instead ofindex.tsat the local package root (a TS-specific behavior). -
Simple jest config hack to make jest inside webapp also run all tests in local packages. commit