跳到主要內容

使用 TypeScript

TypeScript 是一種擴展 JavaScript 的語言,加入了型別定義。新的 React Native 專案預設以 TypeScript 為目標,但也支援 JavaScript 和 Flow。

TypeScript 入門

React Native CLI 建立的新專案,或像 Ignite 這樣流行的範本,預設會使用 TypeScript。

TypeScript 也可與 Expo 搭配使用,Expo 維護 TypeScript 範本,或當 .ts.tsx 檔案加入到你的專案時,會提示你自動安裝和設定 TypeScript。

shell
npx create-expo-app --template

將 TypeScript 加入現有專案

  1. 將 TypeScript、型別和 ESLint 外掛程式加入你的專案。
shell
npm install -D @tsconfig/react-native @types/jest @types/react @types/react-test-renderer typescript
注意

此命令會加入每個相依性的最新版本。版本可能需要變更以符合你的專案使用的現有套件。你可以使用像 React Native Upgrade Helper 這樣的工具來查看 React Native 隨附的版本。

  1. 加入 TypeScript 設定檔。在你的專案根目錄中建立 tsconfig.json
json
{
"extends": "@tsconfig/react-native/tsconfig.json"
}
  1. 將 JavaScript 檔案重新命名為 *.tsx

你應該保持 ./index.js 進入點檔案不動,否則在捆綁生產版本時可能會遇到問題。

  1. 執行 tsc 以型別檢查你的新 TypeScript 檔案。
shell
npx tsc

使用 JavaScript 而非 TypeScript

React Native 預設新的應用程式為 TypeScript,但仍然可以使用 JavaScript。副檔名為 .jsx 的檔案會被視為 JavaScript 而非 TypeScript,且不會進行型別檢查。JavaScript 模組仍然可以被 TypeScript 模組匯入,反之亦然。

TypeScript 和 React Native 如何運作

開箱即用,TypeScript 原始碼會在捆綁期間由 Babel 轉換。我們建議你僅使用 TypeScript 編譯器進行型別檢查。這是為新建立的應用程式 tsc 的預設行為。如果你有現有的 TypeScript 程式碼要移植到 React Native,則使用 Babel 而非 TypeScript 有 一兩個注意事項

React Native + TypeScript 看起來如何

你可以透過 React.Component<Props, State> 為 React 組件的 PropsState 提供介面,這將在使用 JSX 中的該組件時提供型別檢查和編輯器自動完成功能。

components/Hello.tsx
import React from 'react';
import {Button, StyleSheet, Text, View} from 'react-native';

export type Props = {
name: string;
baseEnthusiasmLevel?: number;
};

const Hello: React.FC<Props> = ({
name,
baseEnthusiasmLevel = 0,
}) => {
const [enthusiasmLevel, setEnthusiasmLevel] = React.useState(
baseEnthusiasmLevel,
);

const onIncrement = () =>
setEnthusiasmLevel(enthusiasmLevel + 1);
const onDecrement = () =>
setEnthusiasmLevel(
enthusiasmLevel > 0 ? enthusiasmLevel - 1 : 0,
);

const getExclamationMarks = (numChars: number) =>
numChars > 0 ? Array(numChars + 1).join('!') : '';

return (
<View style={styles.container}>
<Text style={styles.greeting}>
Hello {name}
{getExclamationMarks(enthusiasmLevel)}
</Text>
<View>
<Button
title="Increase enthusiasm"
accessibilityLabel="increment"
onPress={onIncrement}
color="blue"
/>
<Button
title="Decrease enthusiasm"
accessibilityLabel="decrement"
onPress={onDecrement}
color="red"
/>
</View>
</View>
);
};

const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
greeting: {
fontSize: 20,
fontWeight: 'bold',
margin: 16,
},
});

export default Hello;

你可以在 TypeScript playground 中探索更多語法。

在哪裡找到有用的建議

將自訂路徑別名與 TypeScript 搭配使用

若要將自訂路徑別名與 TypeScript 搭配使用,你需要設定路徑別名,使其可同時從 Babel 和 TypeScript 運作。以下是如何操作

  1. 編輯你的 tsconfig.json 以擁有你的 自訂路徑映射。設定 src 根目錄中的任何內容皆可使用,無需前導路徑參考,並允許使用 tests/File.tsx 存取任何測試檔案
diff
{
- "extends": "@tsconfig/react-native/tsconfig.json"
+ "extends": "@tsconfig/react-native/tsconfig.json",
+ "compilerOptions": {
+ "baseUrl": ".",
+ "paths": {
+ "*": ["src/*"],
+ "tests": ["tests/*"],
+ "@components/*": ["src/components/*"],
+ },
+ }
}
  1. babel-plugin-module-resolver 作為開發套件加入到你的專案
shell
npm install --save-dev babel-plugin-module-resolver
  1. 最後,設定你的 babel.config.js(請注意你的 babel.config.js 的語法與你的 tsconfig.json 不同)
diff
{
presets: ['module:metro-react-native-babel-preset'],
+ plugins: [
+ [
+ 'module-resolver',
+ {
+ root: ['./src'],
+ extensions: ['.ios.js', '.android.js', '.js', '.ts', '.tsx', '.json'],
+ alias: {
+ tests: ['./tests/'],
+ "@components": "./src/components",
+ }
+ }
+ ]
+ ]
}