I am trying to run the build (.js files) of typescript with the tsconfig-paths in production, I have no problem running typescript with paths. Just when running the build on production with pm2.
I have tried:
apps: [
{
name: 'app',
script: './dist/index.js',
node_args: '-r ts-node/register -r tsconfig-paths/register',
},
],
TLDR: If as I assume you run info *the* common misunderstanding about tsconfig you may try:
{
apps: [
{
name: 'app',
script: './dist/index.js',
node_args: '-r ts-node/register -r tsconfig-paths/register',
env: {
"TS_NODE_BASEURL": "./dist"
}
},
}
Explanation:
Typescript allows us to specify path aliases so that we don'y have to use ugly relative paths like ../../../../config
. To use this feature typically you would have a tsconfig.json
like this:
...
"outDir": "./dist",
"baseUrl": "./src", /* if your code sits in the /src directory */
"paths": {
"@/*": ["*"]
},
...
Now you can do the following:
import config from "@/config";
It will compile without errors. During the compilation the requested modules are in the src
directory. However:
$ node -r tsconfig-paths/register dist/index.js
Failure! Cannot find module '@/config'
Why is that? Because at runtime config no longer sits inside ./src
but instead can be found in ./dist
.
So how do we handle this?
Fortunately tsconfig-paths allows us to override baseUrl with TS_NODE_BASEURL
env:
$ TS_NODE_BASEURL=./dist node -r tsconfig-paths/register dist/index.js
Success!