React Native项目搭建(react-native + typescript)
1、安装react-nativecli工具
npm i -g react-native-cli
或者
yarn add global react-native-cli
2、创建react-native项目
react-native init MyRnProject
项目名称不允许有中划线,如:my-rn-project
3、添加Typescript
- 安装typescript包
yarn add --dev typescript
- 安装 react-native-typescript-transformer 包
yarn add --dev react-native-typescript-transformer
- 初始化创建tsconfig.json
yarn tsc --init --pretty --jsx react
- 创建Native TypeScript Transformer的配置文件
touch rn-cli.config.js
- 添加React和React Native的类型包
yarn add --dev @types/react @types/react-native
注释tsconfig.json中的以下一行:
{
...
// "allowSyntheticDefaultImports": true,
...
}
向rn-cli.config.js
中添加以下内容:
module.exports = {
getTransformModulePath() {
return require.resolve("react-native-typescript-transformer");
},
getSourceExts() {
return ["ts", "tsx"];
}
};
4、集成ts-jest
测试
添加 ts-jest
依赖
yarn add --dev ts-jest
替换package.json
中的jest
字段为以下内容:
"jest": {
"preset": "react-native",
"moduleFileExtensions": [
"ts",
"tsx",
"js"
],
"transform": {
"^.+\\.(js)$": "<rootDir>/node_modules/babel-jest",
"\\.(ts|tsx)$": "<rootDir>/node_modules/ts-jest/preprocessor.js"
},
"testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$",
"testPathIgnorePatterns": [
"\\.snap$",
"<rootDir>/node_modules/"
],
"cacheDirectory": ".jest/cache"
}
安装类型声明包
yarn add --dev @types/jest @types/react @types/react-native @types/react-test-renderer
忽略.jest 文件夹
# Jest
#
.jest/
至此React Native + TypeScript 项目就搭建完成了