这篇文章主要介绍了如何在 ReactNative 中如何集成 TypeScript,以及咱们遇到的一些问题总结。html
其实关于如何集成TS,RN官方有一篇博客介绍了接入方案,但在参照接入过程当中发现针对老工程部分迁移TS、以及新版本RN并不适用。前端
目前RN 集成 TypeScript 有两个方案:node
方案一: 借助第三方编译插件react-native-typescript-transformerreact
方案二: RN 0.57 版本以后将 babel 升级到了 V7, Babel 从V7开始支持 TypeScript 编译,详情介绍参考这里。android
关于 babel 支持TypeScript编译有如下几个问题须要咱们注意:webpack
babel 只负责在编译期将 TS 编译为JS,并无进行类型校验,这意味着即便咱们代码类型写错了也能编译经过,没有任何提示。不过目前包括 VSCode、WebStorm等开发工具基本支持 TS 语法、类型校验,因此咱们就不须要强依赖编译期类型校验。ios
有一些 TS 特性babel不支持:git
namespaces
bracket style type-assertion
enums
复制代码
上面介绍了现有的两种集成方案的一些详细状况,下面咱们具体说明若是根据不一样 RN 版本已经实际的需求引入TS支持:github
咱们在上面介绍过,对于 RN 版本低于 0.57 的,只能使用react-native-typescript-transformer, 参考官方文档有很详细的步骤指导。web
若是是新项目直接执行下面命令
$ react-native init MyAwesomeProject --template typescript
复制代码
若是是老项目迁移TS,由于新版本使用 babel 编译TS,babel 编译并不会读取tsconfig.json中的配置,咱们须要将相关配置转移到 babel.config.js 或 .babelrc
为何 babel 编译不会读取 tsconfig.json?
上面有介绍过,babel 只是加入了对于TS语法的支持,并无进行类型校验。而 tsconfig.json 的主要做用就是描述了如何进行类型校验,因此 babel并不须要读取这个问题。具体能够参考这个issues。
虽然 babel 编译期并不须要tsconfig.json,但由于咱们还须要vscode、WebStorm 等开发工具支持 TS 校验,项目中仍是须要维护 tsconfig。
具体操做步骤:
$ yarn add metro-react-native-babel-preset @babel/plugin-transform-runtime babel-plugin-module-resolver typescript --dev
$ yarn add --dev @types/react @types/react-native --dev
复制代码
babel.config.js 配置以下:
// babel.config.js
module.exports = {
"presets": [
"module:metro-react-native-babel-preset",
],
"plugins": [
// 解决TS中的 module 引用问题,下面会详细说明
["module-resolver", {
"root": ["./src"],
"extensions": [".js", ".ts", ".tsx", ".ios.js", ".android.js"]
}],
"@babel/plugin-transform-runtime",
],
}
复制代码
固然咱们也能够在大于 0.57 版本中继续使用 react-native-typescript-transformer 方式支持 TS,具体的实现步骤参考这里。
haul 基于 webpack 开发的一套 React Native 编译、打包工具,用来替代 Facebook 官方提供的 metro 打包工具。
我在另一篇文章里有详细介绍 Hook 和 TypeScript 的结合,请移步这里参考。
TS官方支持在 tsconfig 中使用 --baseUrl、--paths 等参数容许咱们使用绝对路径引用其余模块,但咱们按照官方配置使用会有相似以下错误:
error: bundling failed: Error: Unable to resolve module `page/passport/component/index` from `/Users/wangcheng/work/we/rrd-react-native/src/page/passport/login/component/AccountLoginPage.tsx`: Module `page/passport/component/index` does not exist in the Haste module map
This might be related to https://github.com/facebook/react-native/issues/4968
To resolve try the following:
1. Clear watchman watches: `watchman watch-del-all`.
2. Delete the `node_modules` folder: `rm -rf node_modules && npm install`.
3. Reset Metro Bundler cache: `rm -rf /tmp/metro-bundler-cache-*` or `npm start -- --reset-cache`.
4. Remove haste cache: `rm -rf /tmp/haste-map-react-native-packager-*`.
at ModuleResolver.resolveDependency (/Users/wangcheng/work/we/rrd-react-native/node_modules/@react-native-community/cli/node_modules/metro/src/node-haste/DependencyGraph/ModuleResolution.js:183:15)
at ResolutionRequest.resolveDependency (/Users/wangcheng/work/we/rrd-react-native/node_modules/@react-native-community/cli/node_modules/metro/src/node-haste/DependencyGraph/ResolutionRequest.js:52:18)
at DependencyGraph.resolveDependency (/Users/wangcheng/work/we/rrd-react-native/node_modules/@react-native-community/cli/node_modules/metro/src/node-haste/DependencyGraph.js:283:16)
at Object.resolve (/Users/wangcheng/work/we/rrd-react-native/node_modules/@react-native-community/cli/node_modules/metro/src/lib/transformHelpers.js:261:42)
at dependencies.map.result (/Users/wangcheng/work/we/rrd-react-native/node_modules/@react-native-community/cli/node_modules/metro/src/DeltaBundler/traverseDependencies.js:399:31)
at Array.map (<anonymous>)
at resolveDependencies (/Users/wangcheng/work/we/rrd-react-native/node_modules/@react-native-community/cli/node_modules/metro/src/DeltaBundler/traverseDependencies.js:396:18)
at /Users/wangcheng/work/we/rrd-react-native/node_modules/@react-native-community/cli/node_modules/metro/src/DeltaBundler/traverseDependencies.js:269:33
at Generator.next (<anonymous>)
at asyncGeneratorStep (/Users/wangcheng/work/we/rrd-react-native/node_modules/@react-native-community/cli/node_modules/metro/src/DeltaBundler/traverseDependencies.js:87:24)
复制代码
其实缘由很简单,以前也有提到过,babel 编译期间并无读取tsconfig,咱们的 --baseUrl、--paths 等并无生效。在babel中咱们怎么使用绝对路径引用模块呢, 使用插件babel-plugin-module-resolver。
参考配置以下:
"plugins": [
["module-resolver", {
"root": ["./src"],
"extensions": [".js", ".ts", ".tsx", ".ios.js", ".android.js"],
}],
"@babel/plugin-transform-runtime",
]
复制代码
遗憾的是按照上面的配置以后,仍然有报错。而后咱们在issues里面找到了相关问题,目前有一个解决方案是在须要做为绝对路径引入的目录增长一个package.json。举个例子:
// 咱们但愿 component目录做为绝对路径 以下引用
import { slider } from 'component';
// 在component目录增长 package.json
{
"name": "component"
}
复制代码
至此终于能够在TS中使用绝对路径引入模块了。
interface PageProps {
foo?: string;
bar: string;
}
export class PageComponent extends React.Component<PageProps, {}> {
public static defaultProps = {
foo: "default"
};
public render(): JSX.Element {
return (
<span>Hello, { this.props.foo.toUpperCase() }</span>
);
}
}
复制代码
interface PageProps {
foo?: string;
bar: number;
}
const PageComponent: StatelessComponent<PageProps> = (props) => {
return (
<span>Hello, {props.foo}, {props.bar}</span>
);
};
PageComponent.defaultProps = {
foo: "default"
};
复制代码
咱们在TS配置中涉及到了 metro.config.js、.babelrc、tsconfig等一系列的配置文件,这里简单总结下他们之间的关系。
metro:是 Facebook 开发的一个专门为React Native 提供 JS的 bundler,做用和前端中的webpack相似,也有人尝试使用metro做为前端的编译打包工具。
metro 经过调用 babel 提供将ES六、JSX、TS等编译成 ES5的JS代码。
metro.config.js、.babelrc 则是编译期间须要使用的配置文件,tsconfig目前更多的是给 VSCode、WebStorm 等开发工具使用作TS校验。
react-native-typescript-transformer
need react-native-typescript-transformer anymore