[guide] Monorepo with React and TS
這個 template 的功能包含:
- 編譯 React 元件
- 支援 TypeScript 的編譯
- ESLint with TypeScript
- 可以撰寫測試
- 透過 lerna 進行版本控制與專案管理
- 透過 rollup 將專案打包
初始化 lerna
lerna init & lerna create @ pjchender/mono-react-ts-template
$ lerna init
create packages
$ lerna create @mono-react-component-template/core -y
$ lerna create @mono-react-component-template/components -y
Setup TypeScript
setup tsc and build with tsc @ pjchender/mono-react-ts-template
- 在根目錄建立
tsconfig.settings.json,這支檔案是給packages/*中的專案使用的 - 在
packages/*中各自建立tsconfig.json,並且extends來自外層的tsconfig.settings.json - 在根目錄建立
tsconfig.json,透 過在此檔案中設定references來將packages/*中的tsconfig.json關聯起來 - 這時候的做法是透過
tsc來打包專案,但後續會改成使用 babel 搭配@babel/preset-typescript來編譯 TypeScript
Add cleanup script
add clean script to remove dist @ pjchender/mono-react-ts-template
每次專案打包後都會產生 dist 和 *.tsbuildinfo 的檔案,透過 rimraf 這個套件來快速移除這些檔案。
- 安裝
rimraf - 在
packages/*及根目錄的package.json建立對應的clean指令
Setup ESLint with TypeScript
-
安裝和 ESLint、TypeScript 及 React 有關的套件
npm install -D eslint @typescript-eslint/eslint-plugin @typescript-eslint/parsernpm install eslint-config-airbnb-typescript \eslint-plugin-import@^2.22.0 \eslint-plugin-jsx-a11y@^6.3.1 \eslint-plugin-react@^7.20.3 \eslint-plugin-react-hooks@^4.0.8 \@typescript-eslint/eslint-plugin@^4.4.1 \eslint-config-prettier \eslint-plugin-prettier \eslint-plugin-simple-import-sort \--save-devnpm install --save-dev --save-exact prettier -
在根目錄建立
.eslintrc.js,在packages/*中的 eslint 會繼承這支檔案的設定 -
在
packages/*中建立.eslintrc.js,並透過extends繼承根目錄的.eslintrc.js -
建立
.prettierrc -
建立
.eslintignore -
在
packages/*及根目錄的package.json建立對應的lint指令
Testing (Jest)
setup babel for testing(jest) @ pjchender/mono-react-ts-template
-
安裝所需的套件
npm install jest \@types/jest \eslint-plugin-jest \@babel/preset-env \@babel/preset-typescript \--save-dev -
在根目錄建立
babel.config.js,Jest 在執行時預設就會讀這支的設定 -
在
packages/*中各自建立.babelrc並且繼承根目錄的babel.config.js檔 -
在
packages/*及根目錄的package.json建立對應的test指令
rollup
setup rollup with babel to build ts files @ pjchender/mono-react-ts-template