RN 集成 TypeScript方案和問題大全

這篇文章主要介紹瞭如何在 ReactNative 中如何集成 TypeScript,以及咱們遇到的一些問題總結。html

其實關於如何集成TS,RN官方有一篇博客介紹了接入方案,但在參照接入過程當中發現針對老工程部分遷移TS、以及新版本RN並不適用。前端

集成方案

目前RN 集成 TypeScript 有兩個方案:node

方案一: 藉助第三方編譯插件react-native-typescript-transformerreact

方案二: RN 0.57 版本以後將 babel 升級到了 V7, Babel 從V7開始支持 TypeScript 編譯,詳情介紹參考這裏android

關於 babel 支持TypeScript編譯有如下幾個問題須要咱們注意:webpack

  1. babel 只負責在編譯期將 TS 編譯爲JS,並無進行類型校驗,這意味着即便咱們代碼類型寫錯了也能編譯經過,沒有任何提示。不過目前包括 VSCode、WebStorm等開發工具基本支持 TS 語法、類型校驗,因此咱們就不須要強依賴編譯期類型校驗。ios

  2. 有一些 TS 特性babel不支持:git

    namespaces
     bracket style type-assertion
     enums
    複製代碼

具體操做

上面介紹了現有的兩種集成方案的一些詳細狀況,下面咱們具體說明若是根據不一樣 RN 版本已經實際的需求引入TS支持:github

< 0.57版本

咱們在上面介紹過,對於 RN 版本低於 0.57 的,只能使用react-native-typescript-transformer, 參考官方文檔有很詳細的步驟指導。web

> 0.57版本

若是是新項目直接執行下面命令

$ react-native init MyAwesomeProject --template typescript
複製代碼

若是是老項目遷移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-resolver typescript --dev

$ yarn add --dev @types/react @types/react-native --dev
複製代碼

babel.config.js 配置以下:

// babel.config.js
module.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 resolve module `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 Haste module map

This might be related to https://github.com/facebook/react-native/issues/4968
To resolve try the 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 (<anonymous>)
    at resolveDependencies (/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>)
    at asyncGeneratorStep (/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;
}

export class PageComponent extends React.Component<PageProps, {}> {
    public static defaultProps = {
        foo: "default"
    };

    public render(): JSX.Element {
        return (
            <span>Hello, { this.props.foo.toUpperCase() }</span>
        );
    }
}
複製代碼
  • function component的 defaultProps, 組件須要是 StatelessComponent
interface PageProps {
    foo?: string;
    bar: number;
}

const PageComponent: StatelessComponent<PageProps> = (props) => {
    return (
        <span>Hello, {props.foo}, {props.bar}</span>
    );
};

PageComponent.defaultProps = {
    foo: "default"
};
複製代碼

metro & babel

咱們在TS配置中涉及到了 metro.config.js、.babelrc、tsconfig等一系列的配置文件,這裏簡單總結下他們之間的關係。

metro:是 Facebook 開發的一個專門爲React Native 提供 JS的 bundler,做用和前端中的webpack相似,也有人嘗試使用metro做爲前端的編譯打包工具

metro 經過調用 babel 提供將ES六、JSX、TS等編譯成 ES5的JS代碼。

metro.config.js、.babelrc 則是編譯期間須要使用的配置文件,tsconfig目前更多的是給 VSCode、WebStorm 等開發工具使用作TS校驗。

參考文檔

typescript-and-babel-7

react-native-typescript-transformer

need react-native-typescript-transformer anymore

TypeScript Module resolution

default-property-in-typescript

metro 簡介

Using Metro as a web bundler

absolute-paths-for-react-native-typescript

相關文章
相關標籤/搜索