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

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.envfile.

While$npm_package_nameworks fine,$env:IPADDRdoesn'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.envfile 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 evaluateREACT_APP_API_URLusing 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.envfile. Instead, I extended the PowerShell script to "replace" the required variables by working directly in the.envfile.

This is the final run.ps1 PowerShellscript 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
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!