ReactとViteで、importのパスに@/の別名を付ける方法

​​Vite​React,TypeScript

Vite で作った React アプリで import { PriceTag } from '@/components/ui/PriceTag' のように書けるようにするには、tsconfig.app.json の paths と、vite.config.ts の resolve の両方に @/ の設定を書きます。フォルダーの階層が深くなり、../../components/… のような相対パスが長くなってきたときに、src からのパスで import できるようにする設定(パスのエイリアス)です。

片方だけでは、型チェック(tsc)か Vite の開発サーバーのどちらかがファイルを見つけられません。私は検証環境で、設定なし・片方だけ・両方の場合に分けて、tsc -b、開発サーバー、本番ビルドの結果を確かめました。

補足

検証環境は Ubuntu 24.04、Node.js 22.23.4、Vite 8.3.8、@vitejs/plugin-react 6.3.0、React 19.3.1、TypeScript 7.0.2 です。プロジェクトは npm create vite@latest の react-ts テンプレートで作りました。本番ビルドの画面は Playwright 1.63.0 の Chromium で開いて確かめました。エディター(VS Code など)の補完、Vitest でのテスト、CSS の中で @/ を使う書き方、Windows・macOS は試していません。

試したファイルの構成

src の下に3階層のフォルダーを作り、すべて @/ で import しました(主なファイルだけを示します)。

text
src/
├── App.tsx
├── main.tsx
├── components/ui/PriceTag.tsx
├── lib/format.ts
└── pages/settings/PlanPage.tsx
tsx
// src/pages/settings/PlanPage.tsx
// 相対パスなら '../../components/ui/PriceTag' と書くところ
import { PriceTag } from '@/components/ui/PriceTag'

export function PlanPage() {
  return (
    <section>
      <h1>プランの設定</h1>
      <p>
        月額:<PriceTag yen={1200} />
      </p>
    </section>
  )
}

App.tsx は @/pages/settings/PlanPage を、PriceTag.tsx は @/lib/format を同じように import しています。

テンプレートのまま何も設定しないと、npx tsc -b が3つのファイルで TS2307 のエラーを出しました。

text
$ npx tsc -b
src/App.tsx(1,26): error TS2307: Cannot find module '@/pages/settings/PlanPage' or its corresponding type declarations.
src/components/ui/PriceTag.tsx(1,29): error TS2307: Cannot find module '@/lib/format' or its corresponding type declarations.
src/pages/settings/PlanPage.tsx(2,26): error TS2307: Cannot find module '@/components/ui/PriceTag' or its corresponding type declarations.

npx vite build も「Rolldown failed to resolve import "@/pages/settings/PlanPage"」で止まり、開発サーバーでも同じ import が解決できずにエラーになりました。

tsconfig.app.json に paths を書く

TypeScript に @/ の意味を教えるのが、compilerOptions の paths です。react-ts テンプレートでは、src の型チェックの設定は tsconfig.app.json にあるので、こちらに書きます(tsconfig.json は2つの設定ファイルを参照しているだけです)。

json
{
  "compilerOptions": {
    // …テンプレートの設定はそのまま…
    "noFallthroughCasesInSwitch": true,

    /* Path alias */
    "paths": {
      "@/*": ["./src/*"]
    }
  },
  "include": ["src"]
}

@/* の * に入った部分が、右側の ./src/* の * に入ります。./src/* は tsconfig.app.json のある場所からの相対パスです。これで npx tsc -b はエラーなく終わりました。

ただし、TypeScript の公式リファレンスにあるとおり、paths は、同じ対応付けをバンドラーなどほかのツールが実行時やバンドル時に使う、と TypeScript に知らせるための設定です。tsc が出力する import のパスは書き換わりません。実際にファイルを読み込むのは Vite なので、Vite 側の設定も必要になります。

vite.config.ts の resolve.alias で @ を src に向ける

Vite の設定は resolve.alias に書きます。

ts
// vite.config.ts
import { fileURLToPath } from 'node:url'
import react from '@vitejs/plugin-react'
import { defineConfig } from 'vite'

// https://vite.dev/config/
export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url)),
    },
  },
})

Vite のドキュメントには、別名をファイルのパスに向けるときは絶対パスを使うように書かれています。相対パスのままだと、ファイルのパスとして解決されずにそのまま使われるためです。そこで、vite.config.ts のある場所を基準に ./src の絶対パスを作っています。node:url の型は、テンプレートに最初から入っている @types/node で付きました。

この設定と paths の両方がある状態で、開発サーバーは /src/App.tsx と /src/pages/settings/PlanPage.tsx を HTTP のステータス 200 で返しました。npm run build(tsc -b && vite build)も通り、vite preview で開いた画面には「プランの設定」と「月額:1,200円」が表示されました。

resolve.tsconfigPaths なら設定は1か所で済む

検証した Vite 8.3.8 には、tsconfig の paths を Vite がそのまま読む resolve.tsconfigPaths という設定もあります(初期値は false)。resolve.alias の代わりに次のように書くと、@/ の対応は tsconfig.app.json の paths だけに書けば済みます。

ts
// vite.config.ts
import react from '@vitejs/plugin-react'
import { defineConfig } from 'vite'

// https://vite.dev/config/
export default defineConfig({
  plugins: [react()],
  resolve: {
    tsconfigPaths: true,
  },
})

検証環境では、この書き方でも開発サーバーが2つのファイルをステータス 200 で返し、npm run build と vite preview の画面の表示も resolve.alias のときと同じでした。

ただし、Vite のドキュメントの機能の説明にある paths の項には、この機能には性能面のコストがあり、paths で外部ツールの動きを変えることは TypeScript チームが勧めていない、と書かれています。性能面のコストを避けるなら、resolve.alias に書いて、tsconfig の paths と2か所でそろえる書き方になります。

片方だけのときに出るエラー

どちらか一方を書き忘れたときの結果は、次のとおりでした。

設定 tsc -b 開発サーバーで /src/App.tsx を取得 vite build
なし TS2307 500 のエラー エラー
paths だけ 通る 500 のエラー 通る
resolve.alias だけ TS2307 200 単体では試していない(npm run build は tsc -b で止まる)
paths と resolve.alias 通る 200 通る

paths だけのとき、開発サーバーで開いたブラウザには、次のエラーが表示されました。

Viteの開発サーバーのエラー表示。plugin:vite:import-analysis が @/pages/settings/PlanPage を src/App.tsx から解決できないと出ている
tsconfig の paths だけを書いたときに、ブラウザに出たエラー
text
Failed to resolve import "@/pages/settings/PlanPage" from "src/App.tsx". Does the file exist?
ポイント

検証環境では、paths だけのときも npx vite build は成功し、vite preview で開いた画面も正しく表示されました。それでも開発サーバーはエラーになります。ビルドが通るかどうかだけで判断せず、npm run dev でも開いて確かめてください。

逆に resolve.alias だけのときは、開発サーバーは /src/App.tsx をステータス 200 で返しましたが、npm run build は最初の tsc -b で TS2307 を出して終了コード 1 で止まりました。

paths を書くときにつまずきやすい点

paths の右側を ./ なしの "src/*" にすると、TypeScript 7.0 の tsc -b は次のエラーを出しました。

text
tsconfig.app.json(27,15): error TS5090: Non-relative paths are not allowed. Did you forget a leading './'?

TypeScript のリファレンスには、baseUrl を書いた場合は paths がそこからの相対パスになる、という説明があります。ところが TypeScript 7.0 で "baseUrl": "." を足すと、次のエラーになりました。

text
tsconfig.app.json(26,5): error TS5102: Option 'baseUrl' has been removed. Please remove it from your configuration.
  Use '"paths": {"*": ["./*"]}' instead.

TypeScript 7.0 では baseUrl は使えないので、paths の右側を ./src/* のように ./ から書き、baseUrl は書かないようにします。

​Posted by 86