?這篇文章主要介紹了如何在 ReactNative 中如何集成 TypeScript,以及我們遇到的一些問題總結。
其實關于如何集成TS,RN官方有一篇博客介紹了接入方案,但在參照接入過程中發現針對老工程部分遷移TS、以及新版本RN并不適用。
集成方案
目前RN 集成 TypeScript 有兩個方案:
方案一: 借助第三方編譯插件react-native-typescript-transformer
方案二: RN 0.57 版本之后將 babel?升級到了 V7, Babel 從V7開始支持 TypeScript 編譯,詳情介紹參考這里。
關于 babel 支持TypeScript編譯有以下幾個問題需要我們注意:
babel 只負責在編譯期將 TS 編譯為JS,并沒有進行類型校驗,這意味著即使我們代碼類型寫錯了也能編譯通過,沒有任何提示。不過目前包括 VSCode、WebStorm等開發工具基本支持 TS 語法、類型校驗,所以我們就不需要強依賴編譯期類型校驗。
有一些 TS 特性babel不支持:
namespaces bracket styletype-assertion enums
具體操作
上面介紹了現有的兩種集成方案的一些詳細情況,下面我們具體說明如果根據不同 RN 版本已經實際的需求引入TS支持:
< 0.57版本
我們在上面介紹過,對于 RN 版本低于 0.57 的,只能使用react-native-typescript-transformer, 參考官方文檔有很詳細的步驟指導。
> 0.57版本
如果是新項目直接執行下面命令
$ react-native init MyAwesomeProject --templatetypescript
如果是老項目遷移TS,因為新版本使用 babel 編譯TS,babel 編譯并不會讀取tsconfig.json中的配置,我們需要將相關配置轉移到 babel.config.js 或 .babelrc
為什么 babel 編譯不會讀取 tsconfig.json?
上面有介紹過,babel 只是加入了對于TS語法的支持,并沒有進行類型校驗。而 tsconfig.json 的主要作用就是描述了如何進行類型校驗,所以 babel并不需要讀取這個問題。具體可以參考這個issues。
雖然 babel 編譯期并不需要tsconfig.json,但因為我們還需要vscode、WebStorm 等開發工具支持 TS 校驗,項目中還是需要維護 tsconfig。
具體操作步驟:
$ yarn add metro-react-native-babel-preset @babel/plugin-transform-runtime? babel-plugin-module-resolvertypescript--dev$ yarn add --dev @types/react @types/react-native --dev
babel.config.js 配置如下:
// babel.config.jsmodule.exports = {"presets": ["module:metro-react-native-babel-preset",? ? ],"plugins": [? ? ? ? // 解決TS中的 module 引用問題,下面會詳細說明? ? ? ? ["module-resolver", {"root": ["./src"],"extensions": [".js",".ts",".tsx",".ios.js",".android.js"]? ? ? ? }],"@babel/plugin-transform-runtime",? ? ],}
當然我們也可以在大于 0.57 版本中繼續使用 react-native-typescript-transformer 方式支持 TS,具體的實現步驟參考這里。
其他方案
haul?基于 webpack 開發的一套 React Native 編譯、打包工具,用來替代 Facebook 官方提供的 metro 打包工具。
常見問題匯總
React Hook 中使用 TypeScript
我在另外一篇文章里有詳細介紹 Hook 和 TypeScript 的結合,請移步這里參考。
TS中使用絕對路徑
TS官方支持在 tsconfig 中使用 --baseUrl、--paths 等參數允許我們使用絕對路徑引用其他模塊,但我們按照官方配置使用會有類似如下錯誤:
error: bundling failed: Error: Unable to resolvemodule`page/passport/component/index` from `/Users/wangcheng/work/we/rrd-react-native/src/page/passport/login/component/AccountLoginPage.tsx`: Module `page/passport/component/index` does not exist in the HastemodulemapThis might be related to https://github.com/facebook/react-native/issues/4968To resolvetrythe following:1. Clear watchman watches: `watchman watch-del-all`.2. Delete the `node_modules` folder: `rm -rf node_modules && npm install`.3. Reset Metro Bundler cache: `rm -rf /tmp/metro-bundler-cache-*` or `npm start -- --reset-cache`.4. Remove haste cache: `rm -rf /tmp/haste-map-react-native-packager-*`.? ? at ModuleResolver.resolveDependency (/Users/wangcheng/work/we/rrd-react-native/node_modules/@react-native-community/cli/node_modules/metro/src/node-haste/DependencyGraph/ModuleResolution.js:183:15)? ? at ResolutionRequest.resolveDependency (/Users/wangcheng/work/we/rrd-react-native/node_modules/@react-native-community/cli/node_modules/metro/src/node-haste/DependencyGraph/ResolutionRequest.js:52:18)? ? at DependencyGraph.resolveDependency (/Users/wangcheng/work/we/rrd-react-native/node_modules/@react-native-community/cli/node_modules/metro/src/node-haste/DependencyGraph.js:283:16)? ? at Object.resolve (/Users/wangcheng/work/we/rrd-react-native/node_modules/@react-native-community/cli/node_modules/metro/src/lib/transformHelpers.js:261:42)? ? at dependencies.map.result (/Users/wangcheng/work/we/rrd-react-native/node_modules/@react-native-community/cli/node_modules/metro/src/DeltaBundler/traverseDependencies.js:399:31)? ? at Array.map ()atresolveDependencies(/Users/wangcheng/work/we/rrd-react-native/node_modules/@react-native-community/cli/node_modules/metro/src/DeltaBundler/traverseDependencies.js:396:18)at /Users/wangcheng/work/we/rrd-react-native/node_modules/@react-native-community/cli/node_modules/metro/src/DeltaBundler/traverseDependencies.js:269:33? ? at Generator.next(<anonymous>)atasyncGeneratorStep(/Users/wangcheng/work/we/rrd-react-native/node_modules/@react-native-community/cli/node_modules/metro/src/DeltaBundler/traverseDependencies.js:87:24)
其實原因很簡單,之前也有提到過,babel 編譯期間并沒有讀取tsconfig,我們的 --baseUrl、--paths 等并沒有生效。在babel中我們怎么使用絕對路徑引用模塊呢, 使用插件babel-plugin-module-resolver。
參考配置如下:
"plugins": [? ? ["module-resolver", {"root": ["./src"],"extensions": [".js",".ts",".tsx",".ios.js",".android.js"],? ? }],"@babel/plugin-transform-runtime",]
遺憾的是按照上面的配置之后,仍然有報錯。然后我們在issues里面找到了相關問題,目前有一個解決方案是在需要作為絕對路徑引入的目錄增加一個package.json。舉個例子:
// 我們希望 component目錄作為絕對路徑 如下引用import{ slider }from'component';// 在component目錄增加 package.json{"name":"component"}
至此終于可以在TS中使用絕對路徑引入模塊了。
TS 中引入 ESLint
關于 TypeScript 中 defaultProps
class component 的 default props, TS 3.0 以后支持類的靜態屬性 defaultProps
interface PageProps {? ? foo?: string;? ? bar: string;}exportclassPageComponentextendsReact.Component {? ? publicstaticdefaultProps = {foo:"default"};? ? public render(): JSX.Element {return(Hello, { this.props.foo.toUpperCase() });? ? }}
function component的 defaultProps, 組件需要是 StatelessComponent
interface PageProps {? ? foo?: string;? ? bar: number;}constPageComponent: StatelessComponent =(props) =>{return(Hello, {props.foo}, {props.bar});};PageComponent.defaultProps = {foo:"default"};
metro & babel
我們在TS配置中涉及到了 metro.config.js、.babelrc、tsconfig等一系列的配置文件,這里簡單總結下他們之間的關系。
metro:是 Facebook 開發的一個專門為React Native 提供 JS的 bundler,作用和前端中的webpack類似,也有人嘗試使用metro作為前端的編譯打包工具。
metro 通過調用 babel 提供將ES6、JSX、TS等編譯成 ES5的JS代碼。
metro.config.js、.babelrc 則是編譯期間需要使用的配置文件,tsconfig目前更多的是給 VSCode、WebStorm 等開發工具使用做TS校驗。
參考文檔
react-native-typescript-transformer
need react-native-typescript-transformer anymore