0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaScriptからTypeScriptへ移行する

Posted at

初めに

個人サイトを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"]
}

TypeScriptJavaScriptを共存させる場合は

{
    "compilerOptions": {
        "allowJs": true
    }
}

拡張子の変更

js ->ts
jsx->tsx

また、vite.config.js -> vite.config.tsに変更した際、

import react from '@vitejs/plugin-react';

この一文を追加。

型定義を追加

  1. props

    type props = {title: string; children: React.ReactNode;}
    function App({ title,children }: Props)
    
  2. useState

    const [count, setCount] = useState<number>(0);
    
  3. イベントハンドラ

    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~

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?