node.jstypescriptverceltypescript-module-resolution

Cannot find module error with TypeScript in Vercel project


I'm working on a TypeScript project deployed on Vercel and encountering an issue where the module 'stateStorage' cannot be found when imported from another file within the same directory. Here's the error I receive when running 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

Project Structure:

/.
  /api
    - companyContact.ts
    - stateStorage.ts

Code:

companyContact.ts

import { getState, setState } from './stateStorage';

stateStorage.ts

export 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"]
}

Attempts to Resolve:

  1. Verified File Existence: I confirmed that stateStorage.ts exists in the api directory and that the file name is spelled correctly.
  2. Checked Import Statement: I reviewed the import statement in companyContact.ts to ensure it uses the correct relative path (./stateStorage).
  3. Reviewed TypeScript Configuration: I examined the tsconfig.json to ensure that the settings for moduleResolution, esModuleInterop, and other relevant options are correctly configured for a Node.js environment.
  4. Local Testing: I attempted to import stateStorage.ts in a simple TypeScript file locally to see if the issue was specific to the Vercel environment or my project setup.

What I Expected to Happen:

I expected the module stateStorage to be successfully imported into companyContact.ts without any resolution errors, given that both files are in the same directory and the TypeScript configuration is set to handle such imports.

What Actually Happened:

Despite the files being correctly placed and the import paths appearing to be correct, I received a runtime error stating that the module stateStorage could not be found when I ran vercel dev. This error persists specifically in the Vercel deployment environment, suggesting that the issue might be related to how paths are resolved or handled in that environment.

What could be causing this module resolution error, and how can I resolve it?


Solution

  • I think that if you change your import from

    import { getState, setState } from './stateStorage';
    

    to

    import { getState, setState } from './stateStorage.ts';
    

    it might work.