您的位置:首页 > Web前端 > React

如何在React-Native上使用Typescript

2018-11-30 08:41 344 查看

首先安装脚手架:

$ yarn global add create-react-native-app

创建项目:

create-react-native-app xxx

进入项目并启动:

cd xxx
yarn start

如果不用ts,现在就可以正常使用了

 

毕竟要用ts,还得折腾一番:

安装依赖

yarn add typescript tslint -D
yarn add @types/react @types/react-native @types/react-dom -D

我们还需要rimraf,并发地清理从ts编译过来的js文件的输出文件夹,并发地运行npm脚本:

yarn add concurrently rimraf -D

 

设置Typescript config (tsconfig.json)使用tsc命令,或者在项目文件夹中手动创建。

tsc --init

 

需要在tsconfig.json文件手动添加

{
"compilerOptions": {
"module":"es2015",
"target": "es2015",
"jsx": "react",
"rootDir": "src",
"outDir": "build",
"allowSyntheticDefaultImports": true,
"noImplicitAny": true,
"sourceMap": true,
"experimentalDecorators": true,
"preserveConstEnums": true,
"allowJs": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"skipLibCheck": true,
"moduleResolution":"Node"
},
"filesGlob": [
"typings/index.d.ts",
"src/**/*.ts",
"src/**/*.tsx",
"node_modules/typescript/lib/lib.es6.d.ts"
],
"types": [
"react",
"react-dom",
"react-native"
],
"exclude":[
"build",
"node_modules",
"jest.config.js",
"App.js"

],
"compileOnSave": false
}

需要注意一些细节:

我们希望将Typescript应用程序的所有代码存储在src文件夹下的文件夹/子文件夹中。用“rootDir”:“src“,确保你的根目录为src或者也可以手动更改

并把babel.config.js文件扔到这个文件夹内

 

然后安装依赖:

yarn add react-native-scripts

将package.json中的scripts代替为:

"start": "react-native-scripts start",
"eject": "react-native-scripts eject",
"android": "react-native-scripts android",
"ios": "react-native-scripts ios",
"test": "node node_modules/jest/bin/jest.js",
"lint": "tslint src/**/*.ts",
"tsc": "tsc",
"clean": "rimraf build",
"build": "yarn run clean && yarn run tsc --",
"watch": "yarn run build -- -w",
"watchAndRunAndroid": "concurrently \"yarn run watch\" \"yarn run android\"",
"buildRunAndroid": "yarn run build && yarn run watchAndRunAndroid ",
"watchAndRunIOS": "concurrently \"yarn run watch\" \"yarn run ios\"",
"buildRunIOS": "yarn run build && yarn run watchAndRunIOS ",
"watchAndStart": "concurrently \"yarn run watch\" \"yarn run start\"",
"buildAndStart": "yarn run build && yarn run watchAndStart "

将main更改为:

"main":"./node_modules/react-nativescripts/build/bin/crna-entry.js"

 这意味着我们的应用程序从这个crna-entry.js 开始。打开这个文件,你会发现它引用了我们的App.js 

var _App = require('../../../../App');

这意味着它希望app模块位于项目根目录下的app .js 文件中。

ts编译器将会在build文件夹下输出编译过后的.js文件

因此,为了让CRNA能够处理我们已经更改的文件夹结构和Typescript配置,让我们在项目文件夹下添加一个App.js ,它将在src/App中导出我们的App组件。Typescript编译器将输出到build文件夹。

在项目根目录添加一个app.js文件:

import App from './build/App';
export default App;

 

注意创建typescript文件后缀为.tsx

运行命令即可

yarn buildAndStart

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: