一、typescript配置說明(基于react native0.57版本之后,已經(jīng)自帶支持ts。)
(1)配置.babelrc文件(該文件用來設(shè)置轉(zhuǎn)碼的規(guī)則和插件)
{
"presets": [ "module:metro-react-native-babel-preset" ],
"plugins": [
[
"@babel/plugin-proposal-decorators",
{
"legacy": true
}
]
]
}
rn<0.57前module:react-native
rn>=0.57module:metro-react-native-babel-preset
plugin-proposal-decorators在babel7之后,不自帶支持裝飾(注解),需要引入該插件,并配置。(一般mobx會(huì)采用到裝飾)
(2)配置rn-cli.config.js(它是 Packager 的配置文件)
module.exports = {
getTransformModulePath() {
return require.resolve('react-native-typescript-transformer');
},
getSourceExts() {
return ['ts', 'tsx'];
}
}
配置修改ts代碼也能享受RN的Hot reloading特性。
(3)配置tsconfig.json(如果一個(gè)目錄下存在一個(gè)tsconfig.json文件,那么它意味著這個(gè)目錄是TypeScript項(xiàng)目的根目錄。 tsconfig.json文件中指定了用來編譯這個(gè)項(xiàng)目的根文件和編譯選項(xiàng)。)
{
"compilerOptions": {
/* Basic Options */
"target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
"module": "es2015", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
"jsx": "react",
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
"noImplicitAny": false,
"moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
"baseUrl": "./", /* 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
},
"exclude": [
"node_modules"
]
}
配置參數(shù),參考文檔https://www.typescriptlang.org/docs/handbook/tsconfig-json.html
二、集成ts中遇到的坑
let responsePromise = new Promise((resolve, reject) => {
return reject(new Error(`missing is needed data`)) })
在src目錄下使用es6的語法,報(bào)Promise是引用類型,不是值類型,是因?yàn)樵趕rc配置了jsconfig.json,設(shè)置了
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}
experimentalDecorators表示允許在實(shí)驗(yàn)環(huán)境下采用裝飾模式,emitDecoratorMetadata允許元數(shù)據(jù)反射 。刪除掉該文件后,即可成功引用es6中的promise了。
在根界面可以使用ts的特性,比如在tsx中集成jsx,報(bào)
# [Cannot use JSX unless the '--jsx' flag is provided]
(https://stackoverflow.com/questions/50432556/cannot-use-jsxunless-the-jsx-flag-is-provided)
刪除掉jsconfig.json立即就能在編輯器消失紅線提示。
三、實(shí)戰(zhàn)

四、感受
引入ts之后,結(jié)合mobx,ui層和viewmodule層都采用ts,代碼看起來很規(guī)范,(比如讓以前不確定的props和state變得確定了、參對(duì)參數(shù)設(shè)置類型約束),使用強(qiáng)類型,代碼開發(fā)效率提高(支持對(duì)象.屬性),在編譯器就提示出問題,能夠減少debug定位問題的成本等等。