Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass environment variable from command line to yarn

I have a code that reads port number from environment variable or from config. Code looks like this

const port = process.env.PORT || serverConfig.port;
await app.listen(port);

To run app without defining environment variable, I run following yarn command.

yarn start:dev

This command works successfully in Linux shell and Windows command line.

Now, I want to pass environment variable. I tried following,

PORT=2344 yarn start:dev

This commands works successfully in Linux shell but failing in Windows command line. I tried following ways but couldn't get it to work.

Tried: PORT=2344 yarn start:dev

I got error: 'PORT' is not recognized as an internal or external command, operable program or batch file.

Tried: yarn PORT=2344 start:dev

I got error: yarn run v1.17.3 error Command "PORT=2344" not found. info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Any idea please? I know, I can define environment variables from System Properties in Windows. But any way if I can do it from command line?

like image 201
Ishraq Ahmad Avatar asked Sep 08 '19 06:09

Ishraq Ahmad


2 Answers

i'd suggest you use the NPM module called cross-env. it allows adding particular env variables on the command line regardless of platform. with that said, you may try:

$ cross-env PORT=2344 yarn start:dev
like image 63
brightknight08 Avatar answered Nov 09 '22 15:11

brightknight08


You can chain commands on the Windows command prompt with &(or &&). To set a environment variable you need to use the set command.
The result should look like this: set PORT=1234 && yarn start:dev.

HTH, GL, HF :)

like image 6
GuestCoder Avatar answered Nov 09 '22 14:11

GuestCoder