1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Vite+React(TS)でパスのエイリアスを通す方法

1
Posted at

はじめに

コーディング学習の一環として、Chakra UIの環境構築を行っていた。

問題発生箇所

公式ドキュメントのチュートリアルに従って設定を行い、npm run devで開発環境を立ち上げたところ、ブラウザで以下のようにエラーが起きた。

スクリーンショット 2026-01-29 21.22.10.png

内容は、「main.tsxで@/components/ui/provider.tsxのパスでインポートしようとしてるけど、ファイルが見つからないよ」というもの。

しかし、すでに以下のようにtsconfig.app.jsonでpathを定義しており、エディタ上ではエラーが出ておらず、なぜこのようになるのか分からなかった。

スクリーンショット 2026-01-29 21.24.21.png

原因

Viteを使用している場合、Vite独自の設定ファイルにパスの設定をする必要があった。
ルートディレクトリのvite.config.tsに、以下のように記述したところ、エラーが出なくなり、正常に起動するようになった。

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import path from 'path'

// https://vite.dev/config/
export default defineConfig({
  plugins: [
    react({
      babel: {
        plugins: [['babel-plugin-react-compiler']],
      },
    }),
  ],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
    },
  },
})

参考記事

まとめ

今まで、こういったパスやエイリアスの設定を避けて、相対パスでimport文を書いていたが、プロジェクトの規模が大きくなると、そのままでは手間がかかってしまう。
今回のようなパスのエイリアス指定方法を覚えて、もっと効率的に開発を行っていこうと思った。

JISOUのメンバー募集中!

プログラミングコーチングJISOUでは、新たなメンバーを募集しています。
日本一のアウトプットコミュニティでキャリアアップしませんか?
興味のある方は、ぜひホームページをのぞいてみてください!
▼▼▼

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?