react-native-dotenv: https://github.com/goatandsheep/react-native-dotenv
以下 以Typescript 為例
使用步驟
yarn add react-native-dotenvyarn add -D @types/react-native-dotenv- 在babel.config.js文件中 plugins 字段中
[
"module:react-native-dotenv",
{
moduleName: "@env",
path: ".env",
safe: false,
allowUndefined: true,
},
],
- 在需要的地方
import {API_URL} from '@env'
console.log(API_URL)
在根目錄下的.env 文件中
API_URL=http://XXXX.com創(chuàng)建env.d.ts文件 在一個目錄下,如/types
在tsconfig.json 中添加 指定定義的文件路徑
"typeRoots": ["./types"] ,
和compilerOptions 同級
問題點:
在react-native-dotenv 3.3.1版本時,(估計之前版本也有或者是RN的問題)
iOS打Production包時,無法讀取到.env文件
參考: 這個issue https://github.com/goatandsheep/react-native-dotenv/issues/38
雖說是Closed,但好像還有問題,
參考其中一個方法:
對于 iOS,把.env文件 拷貝一個到 /ios目錄下,這樣就能讀取到了。
cp .env ios/ 或 cp .env.production ios/
暫時解決