# 設置 @ 路徑別名
到 tsconfig.json 加入 compilerOptions 的 paths 設定:
- baseUrl:設定為
.,確保路徑別名從此目錄開始計算。 - paths:定義別名,@components/_ 代表
src/components/_。
{
"compilerOptions": {
"baseUrl": ".", // 設定為專案根目錄
"paths": {
"@/*": ["./src/*"] // 確保你的 src 目錄是對的
}
...
}
}
若有使用 Vite 作為打包構建工具的話,還需在 vite.config.ts 裡面加入 alias 設定:
// vite.config.ts
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import tailwindcss from "@tailwindcss/vite";
import path from "path";
// https://vite.dev/config/
export default defineConfig({
plugins: [react(), tailwindcss()],
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
},
},
});
# 解決 Cannot find module '@/lib/utils' 問題
最常見的錯誤就是儘管已設好 path alias,vscode IDE 還是會一直顯示 Cannot find module '@/lib/utils'... 錯誤

修改 jsconfig.json 設定,把 files 及 references 註解掉,並貼上以下設定:
{
// "files": [],
// "references": [{ "path": "./tsconfig.app.json" }, { "path": "./tsconfig.node.json" }],
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
},
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
}
}
之後再回到 IDE 看,就沒有錯誤了
