3. 项目中集成typescript
主要步骤如下:
- 在项目中添加 Typescript
- 在项目中添加 react-native-typescript-transformer
- 在项目中创建默认的
tsconfig.json
文件 - 在项目中添加
rn-cli.config.js
- 在项目中添加react与react-native的声明文件
yarn add --dev typescript
yarn add --dev react-native-typescript-transformer
yarn tsc --init --pretty --jsx react
touch rn-cli.config.js
yarn add --dev @types/react @types/react-native
在rn-cli.config.js
中添加如下代码
module.exports = {
getTransformModulePath() {
return require.resolve('react-native-typescript-transformer');
},
getSourceExts() {
return ['ts', 'tsx'];
},
};
将项目中默认生成的index.js
和App.js
名称修改为index.tsx
和App.tsx
。
再创建global.file.d.ts
,写入如下代码以支持在ts文件中引入.json
文件。
declare module '*.json' {
const src: any;
export default src;
}
简单调整index.tsx
的代码如下:
/**
* @format
* @lint-ignore-every XPLATJSCOPYRIGHT1
*/
import {AppRegistry} from 'react-native';
import App from './App';
import appJson from './app.json';
AppRegistry.registerComponent(appJson.name, () => App);
重新构建项目,启动后一切正常。表示项目已经支持了ts语法。
实践中,为了能够更准确的定位到异常的原因,我们通常都会使用xcode(iOS)
和Android Stuido(android)
来启动项目。
如果需要在 Android Studio
中启动,则使用Android Studio
打开root/android
目录,打开后,Android Studio
会自动同步代码需要的依赖包,如果同步失败,则多试几次即可,确保电脑网络能够过墙。

网友评论