初めに
個人サイトをCreate React Appからviteへ移行した。
そのついでにTypeScriptへも移行しようと思った。
インストール
使用環境:
- Node.js: 9.2.0
- Vite: 7.1.14
- React: 19.1.1
npm install --save-dev typescript @types/react @types/react-dom
tsconfig.jsonの作成
npx tsc --init
以下の内容を記述
{
"compilerOptions": {
"target": "ESNext",
"useDefineForClassFields": true,
"lib": ["DOM", "DOM.Iterable", "ESNext"],
"allowJs": false,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "ESNext",
"moduleResolution": "Node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": ["src"]
}
TypeScriptとJavaScriptを共存させる場合は
{
"compilerOptions": {
"allowJs": true
}
}
拡張子の変更
js ->ts
jsx->tsx
また、vite.config.js -> vite.config.tsに変更した際、
import react from '@vitejs/plugin-react';
この一文を追加。
型定義を追加
-
propstype props = {title: string; children: React.ReactNode;} function App({ title,children }: Props) -
useStateconst [count, setCount] = useState<number>(0); -
イベントハンドラ
const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => { console.log(e.currentTarget); };
備考
*.cssファイルのインポート時にエラーが出た。
その際はsrc/types/global.d.tsを作成し、以下を記述する。
declare module '*.css';
declare module '*.scss';
declare module '*.sass';
終わりに
初めからTypeScriptで書けばよかったと反省。
~Thank you for readin~