週末に社内有志で集まって、React Native眺める会をした。
React Nativeをほとんどやったことがない人間たちが、あーでもないこーでもないと言いながら、TypeScriptを組み合わせてアプリを作ってみた。
React Nativeに興味はあったけど、1人で取り組もうというのはなかなか心理的障壁が高いので、集まってわいわいやってみる会は非常によかったし、ハマりを共有して、解決できるのもよかった。
この後にさらに面白いことをしたのだけど、そもそものTypeScript導入までで躓きがあったので、まずまとめておく。
React Nativeを導入、ビルド
$ brew install node watchman yarn
$ yarn global add react-native-cli
$ react-native init Xxxx
$ cd Xxxx
$ yarn install
$ yarn run react-native run-ios
TypeScriptを入れる
MicrosoftがGitHubにおいている資料を参考にした。
github.com
ただ、若干変わっているので、参考にしつつ、現状に沿ったものにした。
$ mkdir src
$ mv index.js ./src
$ mv ./__tests__/ ./src/__tests__/
./index.js
を編集
import './lib/index';
./src/index.js
を編集
import { AppRegistry } from 'react-native';
import App from './App';
AppRegistry.registerComponent('Xxxx', () => App);
TypeScriptをinstall
$ yarn add typescript ts-jest @types/jest @types/react @types/react-native @types/react-test-renderer --dev
$ yarn tsc --init
./tsconfig.json
を編集 (最終的に以下になった)
{
"compilerOptions": {
/* Basic Options */
"target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
"lib": ["es6", "dom", "esnext.asynciterable"], /* 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-native", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
"sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "./lib", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "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. */
// "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. */
/* 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. */
},
"include": ["./src/"]
}
./package.json
のjestについての部分を以下に置き換える
...
"jest": {
"preset": "react-native",
"moduleFileExtensions": [
"ts",
"tsx",
"js"
],
"transform": {
"^.+\\.(js)$": "<rootDir>/node_modules/babel-jest",
"\\.(ts|tsx)$": "<rootDir>/node_modules/ts-jest/preprocessor.js"
},
"testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$",
"testPathIgnorePatterns": [
"\\.snap$",
"<rootDir>/node_modules/",
"<rootDir>/lib/"
],
"cacheDirectory": ".jest/cache"
}
.js
を .tsx
に置き換える
index.js
以外は、 .tsx
拡張子になる
App.js
を元に、 ./src/
下に App.tsx
を作成する
$ mv App.js ./src/App.tsx
$ vim ./src/App.tsx
// 元の `App.js` を参考にしつつ、TypeScript下で動くコード
import * as React from 'react';
import { Platform, StyleSheet, Text, View } from 'react-native';
const instructions = Platform.select({
ios: 'Press Cmd+R to reload,\n' +
'Cmd+D or shake for dev menu',
android: 'Double tap R on your keyboard to reload,\n' +
'Shake or press menu button for dev menu',
});
type Props = {};
export default class App extends React.Component<Props> {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit App.js
</Text>
<Text style={styles.instructions}>
{instructions}
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
testコードも拡張子を変更しておく
$ mv ./src/__test__/App.js ./src/__test__/App.tsx
TypeScript用のファイルを出力
$ yarn tsc
すると以下のようなエラーになった
yarn run v1.5.1
$ /Users/yutailang0119/Documents/workspace/github.com/ReactNative/Xxxx/node_modules/.bin/tsc
node_modules/@types/react-native/index.d.ts(8734,18): error TS2717: Subsequent property declarations must have the same type. Property 'geolocation' must be of type 'Geolocation', but here has type 'GeolocationStatic'.
error An unexpected error occurred: "Command failed.
Exit code: 2
Command: sh
Arguments: -c /Users/yutailang0119/Documents/workspace/github.com/ReactNative/Xxxx/node_modules/.bin/tsc
Directory: /Users/yutailang0119/Documents/workspace/github.com/ReactNative/Xxxx
Output:
".
info If you think this is a bug, please open a bug report with the information provided in "/Users/yutailang0119/Documents/workspace/github.com/ReactNative/Xxxx/yarn-error.log".
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
よくわからないので "TS2717" で検索すると、 types/react-dom Same type error does not make sense · Issue #23644 · DefinitelyTyped/DefinitelyTyped · GitHub が見つかった。
yarn upgrade @types/react-dom
をやっとけば直るとのことなので、腑に落ちてはないが、一旦これで回避。
$ yarn upgrade @types/react-dom
$ yarn tsc
すると ./lib
下にファイルが出力される。
TypeScript環境でReact Nativeをビルド
$ yarn run react-native run-ios
で表示に問題がなければ成功🎉
.gitignore
に追記
Microsoftの指南書 には .gitignore
に以下も追加するように書いてある。
# TypeScript
#
lib/
# Jest
#
.jest/
まとめ
TypeScriptを使えるようにするまでに結構作業が必要なので、Ansible等でできるようにするとよいんですかね。
おまけ
CodeFormatter
Prettier · Opinionated Code Formatter を使うことにした。
$ yarn add prettier --dev
.prettierrc
に設定を書いて prettier --write filename
とするとフォーマットをかけてくれる。
Scripts
package.json
の scripts にnpm (yarn) のsubcommandとしてのエイリアスを作ることができる。
前述のprettierでのフォーマットも登録した。
...
"scripts": {
"start": "tsc --watch & node node_modules/react-native/local-cli/cli.js start",
"android": "node_modules/.bin/react-native run-android",
"ios": "node_modules/.bin/react-native run-ios",
"test": "jest",
"format": "prettier --write src/**/*.{ts,tsx}"
},
...
$ yarn start
$ yarn ios
$ yarn format
等が使えるようになる
Watchman
$ yarn tsc --watch
としてビルドすると Enable Live Reload
という選択肢が現れる。
これをオンにすると、ファイルの書き換えを検知して、シミュレーターを更新してくれる。
実行を忘れそうなので、 yarn start
に追加した。