Skip to content

Instantly share code, notes, and snippets.

@edoves
Created October 30, 2024 14:39
Show Gist options
  • Save edoves/f68572556b54a943d903cef1e31f273b to your computer and use it in GitHub Desktop.
Save edoves/f68572556b54a943d903cef1e31f273b to your computer and use it in GitHub Desktop.
How to add typescript to an existing vite react app?

How to add typescript to an existing vite react app?

  1. Install typescript, @types/react and @types/react-dom.
npm install --save-dev typescript @types/react @types/react-dom
  1. In packages.json, replace vite build with tsc && vite build.
"build": "vite build"

With 👇

"build": "tsc && vite build"
  1. Rename vite.config.js and main.jsx to vite.config.ts and main.tsx

  2. Configure TypeScript by creating these two files in the root of your project:

tsconfig.json

{
  "compilerOptions": {
    "target": "ESNext",
    "useDefineForClassFields": true,
    "lib": ["DOM", "DOM.Iterable", "ESNext"],
    "allowJs": false,
    "skipLibCheck": true,
    "esModuleInterop": false,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "ESNext",
    "moduleResolution": "Node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": ["src"],
  "references": [{ "path": "./tsconfig.node.json" }]
}

tsconfig.node.json

{
  "compilerOptions": {
    "composite": true,
    "module": "ESNext",
    "moduleResolution": "Node",
    "allowSyntheticDefaultImports": true
  },
  "include": ["vite.config.ts"]
}
  1. Create a file named vite-env.d.ts inside the src/ folder and copy and paste this (with the three slashes at the beginning):
/// <reference types="vite/client" />
  1. In your index.html you should change the name of your script from the old main.jsx to main.tsx like this:
<script type="module" src="/src/main.tsx"></script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment