ReactアプリにTypeScriptを導入する方法
2023-12-8
reactTypeScriptパッケージインストール
1npm i -—save-dev webpack webpack-cli webpack-dev-server ts-loader typescript
設定ファイル作成
webpack.config.js
1const path = require('path') 2 3module.exports = { 4 mode: 'development', 5 entry: './index.tsx', 6 output: { 7 path: path.join(__dirname, '/dist'), 8 filename: 'bundle.js' 9 }, 10 devtool: 'inline-source-map', 11 module: { 12 rules: [ 13 { 14 test: /\.tsx?$/, 15 loader: 'ts-loader', 16 } 17 ] 18 }, 19 resolve: { 20 extensions: ['.ts', '.tsx', '.js', '.json'] 21 } 22}
1npx tsc --init
tsconfig.json
1{ 2 "compilerOptions": { 3 "target": "es5", 4 "lib": [ 5 "dom", 6 "dom.iterable", 7 "esnext" 8 ], 9 "allowJs": true, 10 "skipLibCheck": true, 11 "esModuleInterop": true, 12 "allowSyntheticDefaultImports": true, 13 "strict": true, 14 "forceConsistentCasingInFileNames": true, 15 "noFallthroughCasesInSwitch": true, 16 "module": "esnext", 17 "moduleResolution": "node", 18 "resolveJsonModule": true, 19 "isolatedModules": true, 20 "noEmit": true, 21 "jsx": "react-jsx" 22 }, 23 "include": [ 24 "src" 25 ] 26}
1npm install --save-dev @types/react @types/react-dom --legacy-peer-deps
src/index.tsx
1import React from 'react'; 2import ReactDOM from 'react-dom/client'; 3import './index.css'; 4import App from './App'; 5 6- const root = ReactDOM.createRoot(document.getElementById('root')); 7+ const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement); 8root.render( 9 <React.StrictMode> 10 <App /> 11 </React.StrictMode> 12);