Path Mapping allows you to import modules using absolute paths instead of relative paths. This improves code readability and eliminates the need to update import paths when files are moved.
// β Complex and hard to maintainimport { Button } from "../../components/Button";import { Input } from "../../components/Input";import { formatDate } from "../../utils/format";import { useAuth } from "../../hooks/useAuth";
Problems:
Need to update all imports when file location changes
Complex paths like ../../../
Poor readability
src/pages/users/UserDetail.tsx
Copy
// β Clean and clearimport { Button } from "@/components/Button";import { Input } from "@/components/Input";import { formatDate } from "@/utils/format";import { useAuth } from "@/hooks/useAuth";
Benefits:
Import paths remain the same when file location changes
// Default methodimport { Button } from "@/components/Button";// Specific mappingsimport { Button } from "@components/Button";import { UserPage } from "@pages/UserPage";import { formatDate } from "@utils/format";import { useAuth } from "@hooks/useAuth";import type { User } from "@types/user";
We recommend using only @/*. Too many mappings can cause confusion.
Sonamu itself can be imported without path mapping.
Copy
// β Direct importimport { BaseModelClass, api, transactional } from "sonamu";import { DB } from "sonamu";import { drivers } from "sonamu/storage";import { store } from "sonamu/cache";// β Type importimport type { Context, SonamuConfig } from "sonamu";
Sonamu package structure:
sonamu - Main package
sonamu/storage - Storage drivers
sonamu/cache - Cache drivers
Sonamu provides subpackages through the exports field in package.json.
// β Import types onlyimport type { User } from "@/types/user";import type { Context } from "sonamu";// β Mixed values and typesimport { DB, type Context } from "sonamu";// β Unnecessary import at runtimeimport { User } from "@/types/user";
type imports are removed after compilation, reducing bundle size.
However, Vite config is not needed (moduleResolution: bundler)
Maintain team-wide consistency:
Copy
// β Same across all projects{ "paths": { "@/*": ["./src/*"] }}
Copy
// β All team members use the same methodimport { Button } from "@/components/Button";
Avoid:
Copy
// β Different prefix per projectimport { Button } from "~/components/Button"; // Project Aimport { Button } from "@/components/Button"; // Project Bimport { Button } from "#/components/Button"; // Project C