💭
Reactプロジェクトで main.jsx から main.tsx へ移行
ReactプロジェクトでTypeScriptへの移行時の注意点
ReactプロジェクトをJavaScriptからTypeScriptに移行する際、main.jsx
からmain.tsx
へのファイル名変更だけでなく、いくつかの重要なステップが必要です。以下に、移行プロセス中に遭遇する可能性のある一般的なエラーとその解決策を紹介します。
エラーメッセージ
[vite] Pre-transform error: Failed to load url /src/main.jsx (resolved id: /src/main.jsx). Does the file exist? GET http://localhost:5173/src/main.jsx net::ERR_ABORTED 404 (Not Found)
このエラーは、プロジェクトのエントリーポイントがまだ.jsx
拡張子を使用しているために発生します。.tsx
に変更した後、以下のように修正する必要があります。
main.tsxの更新
src/main.tsx
ファイルを以下のように更新します。
// src/main.tsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import './App.css';
const rootElement = document.getElementById('root');
if (rootElement) {
ReactDOM.createRoot(rootElement).render(
<React.StrictMode>
<App />
</React.StrictMode>
);
} else {
throw new Error('Root element with id "root" not found.');
}
index.htmlの修正
index.html
ファイル内のスクリプトタグのsrc属性を.jsxから.tsxに更新します。
(エラーの原因)
<!doctype html>
<html lang="en">
<!-- ... -->
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>
(正しくsrc="/src/main.tsx"にする)
<!doctype html>
<html lang="en">
<!-- ... -->
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
これらの変更により、TypeScriptへの移行時に発生するエラーを解消できます。この記事が皆さんの役に立つことを願っています。
Discussion