ボールを蹴りたいシステムエンジニア

ボール蹴りが大好きなシステムエンジニア、ボールを蹴る時間確保の為に時間がある時には勉強する。

ReactとViteでの@によるパス指定について

事象

ViteでReactを読み込んでるindex.htmlにアクセスしたところ以下のエラーが出た。

[plugin:vite:import-analysis] Failed to resolve import "@/pages/HogeTest" from "src/App.tsx". Does the file exist?

index.html

<script type="module" src="/src/index.tsx">

index.tsx

import App from './App.tsx'

App.tss

import MasterManagement from '@/pages/HogeTest';
import '@/styles/globals.css';

原因

Viteはtsconfig.jsonのパス設定を自動的に読み取らないため、@/pages/HogeTestのようなパスエイリアスを解決できないらしい。

対策

vite.config.tsにVite用のパスエイリアス設定を追加。
Viteがパスエイリアスを理解できるようになる。
TypeScriptの設定(tsconfig.json)とViteの設定が一致する。

resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
},
},

Reactの@について

この@は、通常プロジェクトのsrcディレクトリを指すように設定されている。
tsconfig.json

"baseUrl": ".",
"paths": {
"@/*": ["src/*"],
"@/components/*": ["src/components/*"],
"@/pages/*": ["src/pages/*"],
"@/hooks/*": ["src/hooks/*"],
"@/services/*": ["src/services/*"],
"@/types/*": ["src/types/*"],
"@/utils/*": ["src/utils/*"],
"@/styles/*": ["src/styles/*"]
}