我想在 React Native 專案中使用目前給定的本機(jī) IP 位址。
因此,我建立了一個(gè) Powershell 腳本文件,用於查找 IP 位址並將其儲(chǔ)存到系統(tǒng)變數(shù) $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
現(xiàn)在我想在我的專案的 .env
檔案中傳遞這個(gè)變數(shù)。
雖然$npm_package_name
工作正常,但$env:IPADDR
似乎不起作用。輸出結(jié)果不是評(píng)估先前定義的環(huán)境變量,而是變數(shù)文字文字本身,即console.log(REACT_APP_API_URL) --> http://$env:IPADDR:3000/
而非評(píng)估的結(jié)果http://192.168.10.4:3000/
。
我的 .env
檔案是這樣創(chuàng)建的。
REACT_APP_API_URL=http://$env:IPADDR:3000/ REACT_APP_NAME=$npm_package_name
那麼,我哪裡做錯(cuò)了?如何使用 PowerShell 環(huán)境變數(shù) $env:IPADDR
動(dòng)態(tài)評(píng)估 REACT_APP_API_URL
?
我發(fā)現(xiàn)無(wú)法在 .env
檔案中本機(jī)擴(kuò)充 Windows 環(huán)境變數(shù)。相反,我擴(kuò)展了 PowerShell 腳本,透過(guò)直接在 .env
檔案中工作來(lái)「替換」所需的變數(shù)。
這是最終的
#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