LoginSignup
9

More than 3 years have passed since last update.

create-react-appで作ったReact SPAをあとからTypeScript対応したい時の手動ワークアラウンド

社内の事情や個人のスキルの問題などではじめはTypeScriptを使わずにReact SPAを作ることになった。
ただ、後からTypeScriptいれようとなった時の覚書。

基本ライン

https://vincenttunru.com/migrate-create-react-app-typescript-to-create-react-app/
この記事の手順通りにやればいけます。

この記事で書くこと

npm start or yarn startしてもtsconfig.jsonなどが作成されなかった場合の力技。
十中八九コードに問題があるとかなんでしょうが、それでも押し通らないといけないときの力技。

準備

部品取りのためにプロジェクトを新規で作ります。

$ npx create-react-app ts-cra --typescript
$ cd ts-cra
$ npm i -S typescript @types/node @types/react @types/react-dom @types/jest
$ npm start

部品取り

npm startでTypeScript用のファイルが生成されます。

$ git status
Untracked files:
  (use "git add <file>..." to include in what will be committed)

    src/react-app-env.d.ts
    tsconfig.json

この2ファイルをmvなどで自分のCRAプロジェクトに移しましょう。

ライブラリインストール

追加する側のPJにもTypeScript系ライブラリが必要です。

$ yarn add -D typescript @types/node @types/react @types/react-dom @types/jest

ドキュメントなどではdependenciesに入れさせてるんですが、@typesとかってdevの方でいいんじゃないかと個人的には思うのです。
ここってなにか理由あるんですかね・・・

実行する

npm startで作られるファイルを手動で放り込んでいるので、これでtsxファイルを入れるとちゃんと判定してくれます。

なお

Flowtypeで中途半端に型をつけていると、そっちの移行作業が発生してイヤッホーorz

TypeScript error in /Users/develop/dashboard/src/AccountInfo.jsx(9,46):
'types' can only be used in a .ts file.  TS8010

     7 | import DashboardCard from './DashbaordCard';
     8 | 
  >  9 | const AccountInfo = ({ username, children }: { username: string, children: React.Node }) => (
       |                                              ^
    10 |   <DashboardCard title="Account Information">
    11 |     <Form>
    12 |       <FormGroup>

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
9