はじめに
TypeScriptでReactアプリを作成する際、TypeScript設定ファイルの「tsconfig.json」に追記しておくと良い設定について記録しておきます。
アプリはnodeインストール済みの環境で以下コマンドを発行して作成したものとします。
npx create-react-app hello-world --template typescript
追記後のtsconfig.json
「"baseUrl": "src"」と「"downlevelIteration": true」を追記しています。
hello-world/tsconfig.json
{"compilerOptions":{"target":"es5","lib":["dom","dom.iterable","esnext"],"allowJs":true,"skipLibCheck":true,"esModuleInterop":true,"allowSyntheticDefaultImports":true,"strict":true,"forceConsistentCasingInFileNames":true,"module":"esnext","moduleResolution":"node","resolveJsonModule":true,"isolatedModules":true,"noEmit":true,"jsx":"react","baseUrl":"src","downlevelIteration":true,},"include":["src"]}
"baseUrl": "src"
追記しておくと、node-modules/
にインストールされていないモジュールをインポートする時(src配下に自分で作成したモジュールなど)、src/
を起点としたパスで指定することができます。
例としてsrc/components/pages/home.tsx
からsrc/components/atoms/button.tsx
を参照する際、この設定が無い場合相対パスをつなげて書かなければならないですが
src/components/pages/home.tsx
import*from'../../atoms/button'
この設定を追記することで
src/components/pages/home.tsx
import*from'components/atoms/button'
このように書くことができます。
"downlevelIteration": true
コンパイルターゲットをES5以前に設定している場合(「"target": "es5"」)でも、ES2015から導入された便利な記述をES5以下で実行できるようよしなに書き下してくれます。
この設定が無ければ新機能を使用した記述によるコンパイルエラーが発生してしまう可能性も有るので、最初から有効にしておくと良いです。
以上です。お疲れ様でした