13

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?

RobC
  • 22,977
  • 20
  • 73
  • 80
lonewarrior556
  • 3,917
  • 2
  • 26
  • 55

1 Answers1

8

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

Lukasz Migut
  • 192
  • 1
  • 3
  • 9
  • Hey sorry, it wasn't just one command, it was a bunch. Question edited to more properly reflect the problem – lonewarrior556 Oct 04 '18 at 11:22
  • You can use this if statement in all your task but instead invoke new script just use command directly in if statement. In this way, you will have one script for production and development environment – Lukasz Migut Oct 04 '18 at 13:03