LoginSignup
0
0

どうもこんにちは、たくびー(@takubii)です。

今回はVite + Reactで作ったプロジェクトを途中からTypeScriptで書けるように設定する方法を共有します。

パッケージのインストール

インストールするバッケージは以下の3つです。

  • typescript
  • @typescript-eslint/eslint-plugin
  • @typescript-eslint/parser
terminal
npm i --save-dev typescript @typescript-eslint/eslint-plugin @typescript-eslint/parser

Configファイルの追加、変更

vite.config.ts
+import { defineConfig } from 'vite'
+import react from '@vitejs/plugin-react'

+// https://vitejs.dev/config/
+export default defineConfig({
+  plugins: [react()],
+})
tsconfig.json
+{
+  "compilerOptions": {
+    "allowImportingTsExtensions": true,
+    "isolatedModules": true,
+    "jsx": "react-jsx",
+    "lib": [
+      "ES2020",
+      "DOM",
+      "DOM.Iterable"
+    ],
+    "module": "ESNext",
+    /* Bundler mode */
+    "moduleResolution": "bundler",
+    "noEmit": true,
+    "noFallthroughCasesInSwitch": true,
+    "noUnusedLocals": true,
+    "noUnusedParameters": true,
+    "resolveJsonModule": true,
+    "skipLibCheck": true,
+    /* Linting */
+    "strict": true,
+    "target": "ES2020",
+    "useDefineForClassFields": true
+  },
+  "include": [
+    "src"
+  ],
+  "references": [
+    {
+      "path": "./tsconfig.node.json"
+    }
+  ]
+}
tsconfig.node.json
+{
+  "compilerOptions": {
+    "allowSyntheticDefaultImports": true,
+    "composite": true,
+    "module": "ESNext",
+    "moduleResolution": "bundler",
+    "skipLibCheck": true,
+    "strict": true
+  },
+  "include": [
+    "vite.config.ts"
+  ]
+}

js(jsx)ファイルをts(tsx)ファイルに置き換えていく

index.html
<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
    ...
    <title>Vite + React</title>
  </head>
  <body>
    <div id="root"></div>
-    <script type="module" src="/src/main.jsx"></script>
+    <script type="module" src="/src/main.tsx"></script>
  </body>
</html>
main.tsx
import React from 'react'
import ReactDOM from 'react-dom/client'
-import App from './App.jsx'
+import App from './App.tsx'
import './index.css'

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
)

後はひたすらJS(JSX)ファイルをTS(TSX)ファイルに置き換えていってください。
ESLintを入れておくと拡張子を変換した時にファイル内でLintエラーを出してくれるので、そこを潰していくと効率よく置き換えができるのでインストール推奨です。

終わりに

私の場合、最初は実装の速さを重視しJavaScriptで実装を行なっていましたが、ある程度のコードベースになってくるとTypeScriptで型の厳密性や補完などの機能が欲しくなってきて思い切って全てのコードを置き換えました。

基本的にパッケージをインストールし、設定ファイルを追加するだけでTypeScriptを使えるようになるので最初はJS,TSどちらから始めても大丈夫だなと感じています。

それでは今回はこのあたりで締めたいと思います。
ここまで読んでいただきありがとうございます。
また機会があればお会いしましょう。

0
0
0

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
  3. You can use dark theme
What you can do with signing up
0
0