I have a project written in Typescript
When developing Locally:
ts-node
is installed as a dev-dependency, The commands are
to start: "ts-node src/index"
to init: "ts-node bin/init"
to init db: "ts-node bin/database-init"
to migrate db: "ts-node bin/database-migrate"
to add users: "ts-node bin/add-users"
When Deployed:
dev-dependencies are dropped, app is transpiled, the commands are
to start: "node src/index"
to init: "node bin/init"
to init db: "node bin/database-init"
to migrate db: "node bin/database-migrate"
to add users: "node bin/add-users"
Thus I am forced to maintain this in my package.json
which will keep growing
"scripts": {
"start": "ts-node src/index",
"start:js": "node src/index",
"init": "ts-node bin/init",
"init:js": "node bin/init",
"db:init": "ts-node bin/db-init",
"db:init:js": "node bin/db-init",
"db:migrate": "ts-node bin/db-migrate",
"db:migrate:js": "node bin/db-migrate",
"add:users": "ts-node bin/add-users",
"add:users:js": "node bin/add-users"
},
I would much rather have a single command that works in both
to do this I have set the following alias in the deployment server
alias ts-node=/usr/bin/node
as such all these now works for both..
"scripts": {
"start": "ts-node src/index",
"init": "ts-node bin/init",
"db:init": "ts-node bin/db-init",
"db:migrate": "ts-node bin/db-migrate",
"add:users": "ts-node bin/add-users",
}
But this is not a great solution and prevents me from deploying it anywhere else.. I prefer to set the name space for right-node
to ts-node || node
inside the package.json
this way it would be portable..
I know that the namespace for all dependencies gets added when running npm scripts
, So this does happen behind the scenes, but is there any built in functionality to do this manually?
I think the best solution is to work with NODE_ENV but first, you need to install:
npm install if-env --save
and then in the script:
"scripts": {
"start": "if-env NODE_ENV=production ?? npm run start:prod || npm run start:dev",
"start:dev": "ts-node src/index",
"start:prod": "node src/index"
}
And on the server you need to set NODE_ENV to production
On Linux:
export NODE_ENV=production
And for production, I suggest using something like pm2 or foverer insted node to start an application