はじめに
create-react-app-typescriptからcreate-react-app v2に移行しましたので、
その手順について共有いたします。
create-react-app v2への移行
https://vincenttunru.com/migrate-create-react-app-typescript-to-create-react-app
に記載されています。下記のほとんどの記載内容は引用です。
STEP1: react-scripts-tsを削除し、react-scriptsをdependenciesに加える(yarnの場合)
yarn remove react-scripts-ts
yarn add react-scripts
STEP2: node scriptsを書き換える
package.jsonのscriptsを先程インストールしたreact-scriptsに修正する
(react-scripts-tsから「-ts」を消す)
変更前
"scripts": {
"start": "react-scripts-ts start",
"build": "react-scripts-ts build",
"test": "react-scripts-ts test --env=jsdom",
"eject": "react-scripts-ts eject"
},
変更後
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
STEP3: configファイルの削除
- tsconfig.json
- tsconfig.prod.json
- tsconfig.test.json
を削除する
STEP4: 開発サーバの実行
yarn start
アプリケーションを実行すると、自動的に
新しいtsconfig.jsonと新規にreact-app-env.d.tsがルートディレクトリ配下に作成されます。
V2移行時の注意点
- 新しいtsconfig.jsonではデフォルトでstrict modeになっているので、
必要に応じてcompilerOptionsを変更する。勿論strict modeの方が望ましい。 - Import文のパスが相対パスしか受け付けないため、絶対パスになっている箇所を相対パスに修正する
※上記の参考サイトではStoryBook使用時の注意点が記載されています。私はStoryBookをプロダクトで使用していないため、本記事では省きますが、使用されている方は参照してください。
Polyfill
既存の記事と重複しますが、V2標準ではIEのサポートを打ち切っています。
ただし、それだと現実問題困るため、CRA公式のpolyfillが公開されてます。
本記事ではIE11への対応を記載しますが、全て公式サイト
(https://facebook.github.io/create-react-app/docs/supported-browsers-features)
(https://github.com/facebook/create-react-app/blob/master/packages/react-app-polyfill/README.md)
に記載済みの内容です。
STEP1: polyfillの追加
本記事では、CRA公式のpolifillのを追加します。
JSファイルを見るとcore-jsをインポートしている為、babel-polyfill等でも問題ないような気がします。
yarn add react-app-polyfill
STEP2: polyfillのインポート
アプリケーションのエントリファイル、index.tsx
の最初に下記2文を追加します。
import 'react-app-polyfill/ie11'
import 'react-app-polyfill/stable'
STEP3: (option)package.jsonの修正
このままでも、buildしたアプリケーションなら、問題無く動作しますが
ローカル環境で実行した場合、polyfillが適用されません。
ローカルでもpolyfillを適用するには、
上のSTEP4実行時に追記されたpackage.jsonのbrowserslistを更に修正します。
developmentの一番下に"IE 11"を追加します。
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version",
"ie 11"
]
}
上記、追加後もpolyfillが適用されない場合は、
node_moduleを全て削除後、もう一度yarn install or npm install
してから確認してみてください。