CODEMemorandum

【React】絶対パスでimportする

ディレクトリの階層が深くなると、importする時に

import type { User } from "../../../types/user";

こんなことになって「いや、深いな…!」となったので、絶対パスでimportできるように設定しました。
(Viteの場合)

① tsconfig.app.json

compilerOptions に paths を追加する。

{
  "compilerOptions": {
    "paths": {
      "@/*": ["./src/*"]
    }
  }
}

② vite.config.ts

こちらにもエイリアスを書く。
path を読み込んで resolve.alias を追加。

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import path from "node:path";

export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: {
      "@": path.resolve(__dirname, "./src"),
    },
  },
});

これでsrcからの絶対パスで書けるようになる

import type { User } from "../../../types/user";

import type { User } from "@/types/user";