rex
rex

Reputation: 3183

How can I use an environment variable in a npm script on windows?

In my package.json file I have a script defined like this:

"scripts": {
    "start": "webpack-dev-server --open --config webpack.dev.js"
}

I want to pass it my hostname, which is a Windows environemnt variable called HOSTNAME. I have tried the following solutions, but neither one seems to work:

"start": "webpack-dev-server --open --config webpack.dev.js --host HOSTNAME"

and

"start": "webpack-dev-server --open --config webpack.dev.js --host %HOSTNAME%"

What am I missing?

Upvotes: 1

Views: 1813

Answers (1)

Mika Sundland
Mika Sundland

Reputation: 18979

The correct syntax on Windows is %envvariable%. It doesn't work for you because hostname is an application (hostname.exe) that outputs the hostname, not an environmental variable. One solution is to use the variable COMPUTERNAME instead.

"start": "webpack-dev-server --open --config webpack.dev.js --host %COMPUTERNAME%"

According to the documentation the hostname tool

Displays the host name portion of the full computer name of the computer.

So COMPUTERNAME might not display entirely what you want, but I would give it a shot. There is some info regarding COMPUTERNAME here.

I tried a few clever tricks, such as storing the output of hostname.exe in a new environment variable:

"start": "hostname > host.txt && set /P HOST= < host.txt && webpack-dev-server --open --config webpack.dev.js --host %HOST%"
"start": "for /f %i in ('hostname') do set HOST=%i && webpack-dev-server --open --config webpack.dev.js --host %HOST%"

I couldn't get it to work.

Upvotes: 1

Related Questions