美文网首页
typescript搭建React Native工程

typescript搭建React Native工程

作者: 何蒙其实很好 | 来源:发表于2019-07-05 16:37 被阅读0次

有一次观摩了前端同事的代码后,对ts+mobx的架构很感兴趣,然后就开始了ts的使用旅程。

在网上浏览了很多帖子教程,但是问题很多,各种报错,后来还是觉着找官方靠谱,于是就到了这个地址:

https://github.com/Microsoft/TypeScript-React-Native-Starter#typescript-react-native-starter

1.创建ReactNative工程

react-nativeinit MyAwesomeProject

2.创建源代码文件夹,把工程自动生成的js代码也迁移到src目录下,至于这个目录其实可以自定义的,也可以按照自己的方式来:

mkdirsrcmv*.jssrc

3.搭建TypeScript环境

npm install -g typescript

4.创建typescript配置文件tsconfig.json,在项目根目录(与node_modules平级)下执行下述命令

tsc --init --pretty --sourceMap --target es2015 --outDir ./lib --modulecommonjs--jsxreact

5.经前端同事建议需要加上一些依赖库,修改tsconfig.json

"lib": ["dom","es2015","es2016","es2017"],

6.另外还要额外增加tsx、ts文件路径和不引入路径

"include": ["typings/**/*.d.ts","src/**/*.ts","src/**/*.tsx"],"exclude": ["node_modules"]

7.我的最终tsconfig.json的配置如下:

{"compilerOptions": {"target":"es6",                          /* Specify ECMAScript target version:'ES3'(default),'ES5','ES2015','ES2016','ES2017', or'ESNEXT'. */"module":"commonjs",                    /* Specify module code generation:'none','commonjs','amd','system','umd','es2015', or'ESNext'. */"lib": ["dom","es2015","es2016","es2017"],                            /* Specify library files to be includedinthe compilation:  */"jsx":"react",                          /* Specify JSX code generation:'preserve','react-native', or'react'. */"sourceMap":true,                        /* Generates corresponding'.map'file. */"outDir":"./lib",                        /* Redirect output structure to the directory. */"strict":true/* Enable all stricttype-checking options. */  },"include": ["typings/**/*.d.ts","src/**/*.ts","src/**/*.tsx"],"exclude": ["node_modules"]}

8.增加node_modules下的依赖

npm install --save-dev@types/jest@types/react@types/react-native@types/react-test-renderer

9.修改js文件后缀为tsx,另外ts下部分语法有变化,原文如下

ReplaceimportReact, {Component}from'react';withimport*asReactfrom'react';Replaceimportrendererfrom'react-test-renderer';withimport*asrendererfrom'react-test-renderer';Rewrite importsfromimportIndexfrom'../index.ios.js'; toimportIndexfrom'../index.ios';,andlikewiseforAndroid. In other words, drop the .js extensionfromyour imports.

10.修改类定义方法

exportdefaultclassAppextendsComponent<{}>修改为:exportdefaultclassAppextendsReact.Component或者exportdefaultclassAppextendsReact.Component

11.由于文件路径发生了变话,需要修改native工程下的url路径:

jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"fallbackResource:nil];

修改为:

jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"lib/index"fallbackResource:nil];

12.最后一步,需要编译ts到js

tsc

如果有错误,可以参照报错去修改。

相关文章

网友评论

      本文标题:typescript搭建React Native工程

      本文链接:https://www.haomeiwen.com/subject/cavehctx.html