使用 TypeScript
TypeScript 是一種擴展 JavaScript 的語言,加入了型別定義。新的 React Native 專案預設以 TypeScript 為目標,但也支援 JavaScript 和 Flow。
TypeScript 入門
由 React Native CLI 建立的新專案,或像 Ignite 這樣流行的範本,預設會使用 TypeScript。
TypeScript 也可與 Expo 搭配使用,Expo 維護 TypeScript 範本,或當 .ts
或 .tsx
檔案加入到你的專案時,會提示你自動安裝和設定 TypeScript。
npx create-expo-app --template
將 TypeScript 加入現有專案
- 將 TypeScript、型別和 ESLint 外掛程式加入你的專案。
- npm
- Yarn
npm install -D @tsconfig/react-native @types/jest @types/react @types/react-test-renderer typescript
yarn add --dev @tsconfig/react-native @types/jest @types/react @types/react-test-renderer typescript
此命令會加入每個相依性的最新版本。版本可能需要變更以符合你的專案使用的現有套件。你可以使用像 React Native Upgrade Helper 這樣的工具來查看 React Native 隨附的版本。
- 加入 TypeScript 設定檔。在你的專案根目錄中建立
tsconfig.json
{
"extends": "@tsconfig/react-native/tsconfig.json"
}
- 將 JavaScript 檔案重新命名為
*.tsx
你應該保持
./index.js
進入點檔案不動,否則在捆綁生產版本時可能會遇到問題。
- 執行
tsc
以型別檢查你的新 TypeScript 檔案。
- npm
- Yarn
npx tsc
yarn 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 組件的 Props 和 State 提供介面,這將在使用 JSX 中的該組件時提供型別檢查和編輯器自動完成功能。
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 手冊
- React 關於 TypeScript 的文件
- React + TypeScript 速查表 對於如何將 React 與 TypeScript 一起使用有很好的概述
將自訂路徑別名與 TypeScript 搭配使用
若要將自訂路徑別名與 TypeScript 搭配使用,你需要設定路徑別名,使其可同時從 Babel 和 TypeScript 運作。以下是如何操作
- 編輯你的
tsconfig.json
以擁有你的 自訂路徑映射。設定src
根目錄中的任何內容皆可使用,無需前導路徑參考,並允許使用tests/File.tsx
存取任何測試檔案
{
- "extends": "@tsconfig/react-native/tsconfig.json"
+ "extends": "@tsconfig/react-native/tsconfig.json",
+ "compilerOptions": {
+ "baseUrl": ".",
+ "paths": {
+ "*": ["src/*"],
+ "tests": ["tests/*"],
+ "@components/*": ["src/components/*"],
+ },
+ }
}
- 將
babel-plugin-module-resolver
作為開發套件加入到你的專案
- npm
- Yarn
npm install --save-dev babel-plugin-module-resolver
yarn add --dev babel-plugin-module-resolver
- 最後,設定你的
babel.config.js
(請注意你的babel.config.js
的語法與你的tsconfig.json
不同)
{
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",
+ }
+ }
+ ]
+ ]
}