DEV Community


Posted on • Updated on

Path mapping with Vercel Functions node.js typescript

TLDR; Problem: path mappings in typescript Vercel Functions don't work. Solution: Compile your typescript before handing it over to Vercel! Works in local and production.

So you are super excited to port over your serverless functions to Vercel (Serverless) Functions and of course you used Typescript and path mappings (aka the import from @mylib stuff)... but then you realized path mappings don't work getting the error Can't find module x when you make the api call. You first think its your tsconfig.json setup or something to do with filename case sensitivity and git .. but it isn't you.. it's me.. I mean, it's Vercel

Can't find module x error with vercel functions

Indeed, if you actually read the docs you will see it says path mappings don't work:

Most options are supported aside from "Path Mappings" and "Project References".

This is specifically for Vue builds because Next has its own setup for serverless functions in Vercel.

Here is a solution

Basically we are going to use a different folder to for our typscript version of the Vercel Functions and then compile them with the output directory being the /api folder that Vercel asks you to use for its serverless functions.

  1. Create a source folder say /api-src for your serverless functions
  2. Create a tsconfig.json with path mappings, in that folder because that is what the typescript compiler will read, add the outDir property to the /api (that's because Vercel wants serverless functions in the root /api folder
  3. Install typescrypt and tsc-alias yarn global add typescript tsc-alias

Creation of api-src folder

tsc-alias is so that it replaces the @lib with the absolute path, once compiled to javascript.

  1. Run tsc && tsc-alias from the /api-src folder

After running tsc command

A /api folder gets created (because we told it to in the outDir value in the tsconfig.json in the /api-src folder) and the code gets compiled to javascript. Notice the .map files, those are because we want debugging to be easier. That is set by sourceMap : true value in the tsconfig.

Now you can run vercel dev and no more Can't find module x problems.

Try it out! Let me know if I missed something!


  1. Consider adding dom to your lib array in tsconfig to avoid errors in compilations with some modules.
  2. Consider moving the .ts files to a subfolder api-src/src so separate code from tooling. This will also help with project references if you have any
  3. As an alternative to tsc-alias you can use tscpaths, which works well in conjunction with tsc-watch for live development: tsc-watch --build --onSuccess "tscpaths -p tsconfig.json -s ./src"

Top comments (0)

Want to Create an Account?
Now it's your turn!
🗒 Share a tutorial
🤔 Reflect on your coding journey
❓ Ask a question

Create an account to join hundreds of thousands of DEV members on their journey.