有一次观摩了前端同事的代码后,对ts+mobx的架构很感兴趣,然后就开始了ts的使用旅程。
在网上浏览了很多帖子教程,但是问题很多,各种报错,后来还是觉着找官方靠谱,于是就到了这个地址:
https://github.com/Microsoft/TypeScript-React-Native-Starter#typescript-react-native-starter
1.创建ReactNative工程
react-native init MyAwesomeProject
2.创建源代码文件夹,把工程自动生成的js代码也迁移到src目录下,至于这个目录其实可以自定义的,也可以按照自己的方式来:
mkdir src
mv *.js src
3.搭建TypeScript环境
npm install -g typescript
4.创建typescript配置文件tsconfig.json,在项目根目录(与node_modules平级)下执行下述命令
tsc --init --pretty --sourceMap --target es2015 --outDir ./lib --module commonjs --jsx react
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 included in the 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 strict type-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下部分语法有变化,原文如下
Replace import React, {Component} from 'react'; with import * as React from 'react';
Replace import renderer from 'react-test-renderer'; with import * as renderer from 'react-test-renderer';
Rewrite imports from import Index from '../index.ios.js'; to import Index from '../index.ios';, and likewise for Android. In other words, drop the .js extension from your imports.
10.修改类定义方法
export default class App extends Component<{}>
修改为:
export default class App extends React.Component<any, any>
或者
export default class App extends React.Component
11.由于文件路径发生了变话,需要修改native工程下的url路径:
jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
修改为:
jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"lib/index" fallbackResource:nil];
12.最后一步,需要编译ts到js
tsc
如果有错误,可以参照报错去修改。
网友评论