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
Indeed, if you actually read the docs you will see it says path mappings don't work: https://vercel.com/docs/concepts/functions/serverless-functions/runtimes/node-js#using-typescript-with-the-node.js-runtime
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.
- Create a source folder say
/api-src
for your serverless functions - Create a
tsconfig.json
with path mappings, in that folder because that is what the typescript compiler will read, add theoutDir
property to the/api
(that's because Vercel wants serverless functions in the root/api
folder - Install typescrypt and tsc-alias
yarn global add typescript tsc-alias
tsc-alias
is so that it replaces the @lib
with the absolute path, once compiled to javascript.
- Run
tsc && tsc-alias
from the/api-src
folder
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!
PS:
- Consider adding
dom
to yourlib
array in tsconfig to avoid errors in compilations with some modules. - Consider moving the
.ts
files to a subfolderapi-src/src
so separate code from tooling. This will also help with project references if you have any - As an alternative to
tsc-alias
you can usetscpaths
, which works well in conjunction with tsc-watch for live development:tsc-watch --build --onSuccess "tscpaths -p tsconfig.json -s ./src"
Top comments (0)