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?

React(Vite)でパスエイリアスを設定する

1
Posted at

相対パスが深くなると import が読みにくくなります。

import Btn from "../../../../components/ui/Btn";

これを @ui/Btn のように短く書けるのが「パスエイリアス」です。

@ui/Btn は、実行時に Vite が

@uiresources/js/components/ui

に置き換えて、実際のファイルを探しにいきます。

手順

1) パスを抑える

例:Btn が配下にあるならresources/js/components/ui/Btn.jsx にあれば、

@uiresources/js/components/ui を指すのが自然です。

2) vite.config.js

import path from "path";

export default defineConfig({
  resolve: {
    alias: {
      "@ui": path.resolve(__dirname, "resources/js/components/ui"),
    },
  },
});

これで import Btn from "@ui/Btn"; が実行時に解決できます。

3) jsconfig.json

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@ui/*": ["resources/js/components/ui/*"]
    }
  },
  "include": ["resources/js/**/*"]
}

これを入れると VSCode の補完やジャンプが効きます(Viteとは別担当)。

jsconfig.jsonがない場合は作成しましょう。

まとめ

  • Vite設定(実行用)vite.config.js

  • エディタ設定(補完用)jsconfig.json

  • 両方とも 同じ実フォルダを指すように揃える

    これで @ui/Btn が安定して使えるようになります。

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?