node.js - Vercel 專案中使用 TypeScript 時找不到模組錯誤
我正在進行一個部署在 Vercel 上的 TypeScript 專案,並遇到一個問題:當我從同一目錄中的另一個文件導入模組 'stateStorage' 時,系統找不到該模組。以下是我在執行 vercel dev 時收到的錯誤訊息:
Error: Cannot find module '/Users/aidan/work/real-estate/forecasa-serverless-functions-express/api/stateStorage' imported from /Users/aidan/work/real-estate/forecasa-serverless-functions-express/api/companyContact.ts
專案結構:
/.
/api
- companyContact.ts
- stateStorage.ts
程式碼:
companyContact.tsimport { getState, setState } from './stateStorage';
stateStorage.tsexport const getState = () => { ... };
export const setState = () => { ... };
tsconfig.json{
"compilerOptions": {
"module": "ESNext",
"target": "ESNext",
"moduleResolution": "node",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
},
"include": ["api/**/*", "api/stateStorage.ts"],
"exclude": ["node_modules"]
}
嘗試解決:
- 已驗證的檔案存在性: 我已確認
stateStorage.ts存在於api目錄中,且檔案名稱拼寫正確。 - 檢查過的匯入語句: 我檢查了
companyContact.ts中的匯入語句,以確保它使用了正確的相對路徑(./stateStorage)。 - 檢閱過的 TypeScript 配置: 我檢查了
tsconfig.json,以確保moduleResolution、esModuleInterop以及其他相關選項對 Node.js 環境配置正確。 - 本地測試:我嘗試在本地的一個簡單 TypeScript 文件中導入
stateStorage.ts,以查看問題是特定於 Vercel 環境還是我的專案設定。
我預期會發生的事情:
我預期模組 stateStorage 能夠成功匯入到 companyContact.ts 中而不會出現解析錯誤,因為兩個檔案位於同一目錄,且 TypeScript 配置已設置為處理此類匯入。
實際發生的事情:
儘管檔案已正確放置且匯入路徑看起來正確,但當我執行 vercel dev 時,仍收到運行時錯誤,指出找不到模組 stateStorage。這個錯誤特別在 Vercel 部署環境中持續存在,這表明問題可能與該環境中路徑的解析或處理方式有關。
這個模塊解析錯誤可能是由什麼引起的,我該如何解決它?
答案#1
我認為如果你改變你的進口自
import { getState, setState } from './stateStorage';
到
import { getState, setState } from './stateStorage.ts';
它可能有效。
