React Native开发APP之(初始化TypeScript版本React Native 0.60.X项目)

1,549 阅读6分钟

React Native升级到0.60.0以后,有了很明显的变化,具体可以参见React Native 0.60 新特性一览。个人看来对于开发者来说有几个明显的变化要需要注意的:

a.移除Lean Core

WebViewNetInfo从React Native 的 repo 中迁移出来, WebViewNetInfo, 需要单独安装以下两个库react-native-webview@react-native-community/netinfo

b.Native Modules现在已自动链接

React Native CLI 的团队已经对称为autolinking的 native module 链接进行了重大改进!大多数场景不再需要使用react-native link。与此同时,该团队对整个链接过程进行了彻底改革。确保使用react-native unlink来取消预先存在的依赖关系。也就是说,之前引用第三方原生库的时候,一般情况下不再需要运行react-native link

c.默认使用CocoaPods

首次初始化项目和安装完第三方库以后,一般情况下需要用CocoaPods来完成iOS端的项目依赖,具体操作为进行项目根目录后执行:

cd ios && pod instal

下面再详细地介绍一下怎样创建一个React Native0.60.X项目,并且引入TypeScript支持(笔者的电脑系统为macOS 10.14.6, Xcode版本为10.3),然后版本一步步地运行起来的。

  1. 初始化React Native0.60.X项目(具体环境配置可参考链接

在终端依次运行以下命令:

npm install -g yarn react-native-cli
react-native init AwesomeProject
cd AwesomeProject && npm i

这里用react-native init 初始化的项目已经默认将react-native的生成为最新的发布版本,如果想要从老版本切换到最新的版本,个人认为这是最快捷的一种方式(笔者之前尝试过其他升级方式,但都因为各种冲突而最终放弃,最终是初始化新的项目,把原来的项目目录再复制过来,然后再解决新老版本的差异问题)。

另外值得提出的是,原来初始化项目之后,再执行 npm i安装好相应的依赖之后,再运行react-native run-ios,等待一段时间之后,会在模拟器上运行起来官方的示例程序。但前面讲过,0.60.0版本之后,默认使用 CocoaPods来安装iOS依赖且Native Modules现在已自动链接,此时如果直接运行行react-native run-ios,会直接报错,在模拟器上看不到我们预期的结果。 此时应该先用CocoaPods来安装iOS端的依赖,进行工程根目录,运行以下命令:

cd ios && pod install

如果是第一次运行pod install,需要耐心等待片刻,直到出现以下截图的内容,说明已经安装好了iOS端的依赖。

然后再运行下以命令:

cd .. && react-native run-ios

不出意外,最终会运行成功,并且在模拟器上看到如下预期的结果。

这里有一点需要提醒一下,见上面用pod install安装依赖成功之后截图的最后几行,下次如果要用xCode打开iOS项目时,应该直接双击打开AwesomeProject.xcworkspace而不是AwesomeProject.xcodeproj,否则在xCode运行调试和打包都会报错。

  1. 项目增加TypeScript支持 具体的配置方法官方文档已经写的很详细了。可以参考参考: Using TypeScript with React Native 下面介绍一下几个主要的流程:

首先依次安装以下依赖包:

npm install typescript --save-dev 
npm install react-native-typescript-transformer --save-dev
npm install @types/react --save-dev
npm install @types/react-native --save-dev

再运行:

yarn tsc --init --pretty --jsx react

这样会在项目的根目录生成tsconfig.json文件,按照官方的说法,要打开**"allowSyntheticDefaultImports": true**这一行的注释,tsconfig.json的主要内容如下:

{
  "compilerOptions": {
    /* Basic Options */
    // "incremental": true,                   /* Enable incremental compilation */
    "target": "ESNEXT",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
    "module": "commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
    // "lib": [],                             /* Specify library files to be included in the compilation. */
    "allowJs": true,                       /* Allow javascript files to be compiled. */
    // "checkJs": true,                       /* Report errors in .js files. */
    "jsx": "react",                           /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
    // "declaration": true,                   /* Generates corresponding '.d.ts' file. */
    // "declarationMap": true,                /* Generates a sourcemap for each corresponding '.d.ts' file. */
    // "sourceMap": true,                     /* Generates corresponding '.map' file. */
    // "outFile": "./",                       /* Concatenate and emit output to single file. */
    // "outDir": "./",                        /* Redirect output structure to the directory. */
    // "rootDir": "./",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    // "composite": true,                     /* Enable project compilation */
    // "tsBuildInfoFile": "./",               /* Specify file to store incremental compilation information */
    // "removeComments": true,                /* Do not emit comments to output. */
    // "noEmit": true,                        /* Do not emit outputs. */
    // "importHelpers": true,                 /* Import emit helpers from 'tslib'. */
    // "downlevelIteration": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
    // "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

    /* Strict Type-Checking Options */
    "strict": true,                           /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true,              /* Enable strict null checks. */
    // "strictFunctionTypes": true,           /* Enable strict checking of function types. */
    // "strictBindCallApply": true,           /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
    // "strictPropertyInitialization": true,  /* Enable strict checking of property initialization in classes. */
    // "noImplicitThis": true,                /* Raise error on 'this' expressions with an implied 'any' type. */
    // "alwaysStrict": true,                  /* Parse in strict mode and emit "use strict" for each source file. */

    /* Additional Checks */
    // "noUnusedLocals": true,                /* Report errors on unused locals. */
    // "noUnusedParameters": true,            /* Report errors on unused parameters. */
    // "noImplicitReturns": true,             /* Report error when not all code paths in function return a value. */
    // "noFallthroughCasesInSwitch": true,    /* Report errors for fallthrough cases in switch statement. */

    /* Module Resolution Options */
    // "moduleResolution": "node",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    // "baseUrl": "./",                       /* Base directory to resolve non-absolute module names. */
    // "paths": {},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
    // "rootDirs": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */
    // "typeRoots": [],                       /* List of folders to include type definitions from. */
    // "types": [],                           /* Type declaration files to be included in compilation. */
    "allowSyntheticDefaultImports": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
    "esModuleInterop": true                   /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    // "preserveSymlinks": true,              /* Do not resolve the real path of symlinks. */
    // "allowUmdGlobalAccess": true,          /* Allow accessing UMD globals from modules. */

    /* Source Map Options */
    // "sourceRoot": "",                      /* Specify the location where debugger should locate TypeScript files instead of source locations. */
    // "mapRoot": "",                         /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,               /* Emit a single file with source maps instead of having a separate file. */
    // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

    /* Experimental Options */
    // "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
    // "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */
  },
  "exclude": ["node_modules", "babel.config.js", "metro.config.js", "jest.config.js"]
}

然后再在项目根目录下创建rn-cli.config.js文件,填写以下内容:

module.exports = {
  getTransformModulePath() {
    return require.resolve('react-native-typescript-transformer');
  },
  getSourceExts() {
    return ['ts', 'tsx'];
  },
};

这样,React-Native项目支持TypeScript语法的主要配置就基本完成了。把项目根目录下的index.js修改为index.ts, 把App.js修改为App.tsx, 然后再执行react-native run-ios在模拟器上运行程序,不出意外,可以看到前端同样的默认界面。 到这里为止,就已经创建好了React-Native 0.60.X最新版的默认初始化项目,并且已经配置好TypeScript语法支持。在后续的文章中会给大家一起分享如何一步步创建简单实用的APP,敬请期待吧!