Typescript Path Alias 設定及錯誤解決

Posted by Young on 2025-02-10
Estimated Reading Time 1 Minutes
Words 373 In Total

設置 @ 路徑別名

tsconfig.json 加入 compilerOptionspaths 設定:

  • baseUrl:設定為 .,確保路徑別名從此目錄開始計算。
  • paths:定義別名,@components/_ 代表 src/components/_
1
2
3
4
5
6
7
8
9
{
"compilerOptions": {
"baseUrl": ".", // 設定為專案根目錄
"paths": {
"@/*": ["./src/*"] // 確保你的 src 目錄是對的
}
...
}
}

若有使用 Vite 作為打包構建工具的話,還需在 vite.config.ts 裡面加入 alias 設定:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 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'... 錯誤

alias_error

修改 jsconfig.json 設定,把 filesreferences 註解掉,並貼上以下設定:

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
{
// "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 看,就沒有錯誤了


若您覺得這篇文章對您有幫助,歡迎分享出去讓更多人看到⊂◉‿◉つ~


留言版