設置 @ 路徑別名
到 tsconfig.json
加入 compilerOptions
的 paths
設定:
- baseUrl:設定為
.
,確保路徑別名從此目錄開始計算。
- paths:定義別名,@components/_ 代表
src/components/_
。
1 2 3 4 5 6 7 8 9
| { "compilerOptions": { "baseUrl": ".", "paths": { "@/*": ["./src/*"] } ... } }
|
若有使用 Vite 作為打包構建工具的話,還需在 vite.config.ts
裡面加入 alias
設定:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| import { defineConfig } from "vite"; import react from "@vitejs/plugin-react"; import tailwindcss from "@tailwindcss/vite"; import path from "path";
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
註解掉,並貼上以下設定:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| { "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 看,就沒有錯誤了
若您覺得這篇文章對您有幫助,歡迎分享出去讓更多人看到⊂◉‿◉つ~
留言版