Windows powershell environment variables in React-native .env file?
P粉431220279
P粉431220279 2023-09-14 10:00:27
0
1
689

I want to use the current given local IP address in the React Native project.

So I created a Powershell script file that finds the IP address and saves it into the system variable $env:IPADDR.

Write-Host "Getting current IP Address"
$env:IPADDR = (Get-WmiObject -Class Win32_NetworkAdapterConfiguration | where {$_.DHCPEnabled -ne $null -and $_.DefaultIPGateway -ne $null}).IPAddress | Select-Object -First 1
Write-Host "    ---->" $env:IPADDR

Now I want to pass this variable in my project's .env file.

While $npm_package_name works fine, $env:IPADDR doesn't seem to work. The output result is not the evaluation of the previously defined environment variable, but the variable literal text itself, that is, console.log(REACT_APP_API_URL) --> http://$env:IPADDR:3000/ instead of the result of the evaluationhttp://192.168.10.4:3000/.

My .env file is created like this.

REACT_APP_API_URL=http://$env:IPADDR:3000/
REACT_APP_NAME=$npm_package_name

So, what did I do wrong? How do I dynamically evaluate REACT_APP_API_URL using the PowerShell environment variable $env:IPADDR?

P粉431220279
P粉431220279

reply all(1)
P粉976737101

I discovered that Windows environment variables cannot be expanded natively in the .env file. Instead, I extended the PowerShell script to "replace" the required variables by working directly in the .env file.

This is the final run.ps1 PowerShell script file.

#Find local IP addr and save it to $env:IPADDR variable
Write-Host "Getting current IP Address"
$env:IPADDR = (Get-WmiObject -Class Win32_NetworkAdapterConfiguration | where {$_.DHCPEnabled -ne $null -and $_.DefaultIPGateway -ne $null}).IPAddress | Select-Object -First 1
Write-Host "    ---->" $env:IPADDR

#Replace the value of the key [REACT_APP_API_URL] with the new server ie http://xxx.xxx.xxx.xxx:3000/
$regex = '(?<=REACT_APP_API_URL=)[^=]*'
$file = '.env'
$addr = 'http://' + $env:IPADDR + ':3000/'
(Get-Content $file) -replace $regex, $addr | Set-Content $file

#Start NPM script
npm run start
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template