我正在为TypeScript (如here )设置这个库
我的env
API_KEY=someKey..我正在设置type/env.d.ts
declare module '@env' {
export const API_KEY: string;
}我的babel.config.ts
module.exports = function (api) {
api.cache(true);
return {
presets: ["babel-preset-expo"],
plugins: [
[
"module:react-native-dotenv",
{
moduleName: "@env",
path: ".env",
},
],
],
};
};我的config.ts:
import API_KEY from '@env'
export default {API_KEY};package.json
"dependencies": {
"@types/react-native-dotenv": "^0.2.0",
"expo": "~42.0.1",
"expo-status-bar": "~1.0.4",
"foo": "^0.0.7",
"moment": "^2.29.1",
"react": "16.13.1",
"react-dom": "16.13.1",
"react-native": "https://github.com/expo/react-native/archive/sdk-42.0.0.tar.gz",
"react-native-config": "^1.4.5",
"react-native-dotenv": "^3.1.1",
"react-native-web": "~0.13.12",
"styled-components": "^5.3.0"
},以及我使用API_KEYweather.ts的这个文件
Import axios from "axios";
import config from "../../config";
class WeatherService {
FetchCoordinatesHandler(city) {
return axios.get(`weather`, {
params: {
q: city,
units: "metric",
appid: config.API_KEY
},
});
}
FetchWeatherByCoordinatesHandler({lon, lat}) {
return axios.get(`onecall`, {
params: {
lat: lat,
lon: lon,
units: "metric",
appid: config.API_KEY
},
});
}
}
const weatherServiceInstance = new WeatherService();
export default weatherServiceInstance;我在控制台上看到了这个:
Android Bundling failed 8987ms
Unable to resolve module @env from C:\IT\ReactNative\weather-app\weather-app\config.js: @env could not be found within the project or in these directories:
node_modules
..\node_modules
> 1 | import API_KEY from '@env'
| ^
2 |
3 | export default {API_KEY};

请帮助:(我不知道该怎么办,我在网上到处找过了。也许我的依赖关系没有最新版本的东西。
ATTENTION,当我将模块从@env更改为'react-native-dotenv'时,仍然会出现错误,但也会出现其他一些错误:
Android Bundling failed 5334ms
Unable to resolve module fs from C:\IT\ReactNative\weather-app\weather-app\node_modules\react-native-dotenv\index.js: fs could not be found within the project or in t
hese directories:
node_modules
..\node_modules
> 1 | const {readFileSync} = require('fs')
| ^
2 | const dotenv = require('dotenv')
3 |
4 | function parseDotenvFile(path, verbose = false) {

我希望任何人帮助我,谢谢:)
发布于 2022-07-04 19:03:14
fs的问题是这个模块在移动包中不存在,我有同样的问题,我回顾了关于这个项目的几页,但是我没有找到答案,也许这会有帮助,我重新配置了我的环境配置,
依赖关系:
yarn add dotenv react-native-dotenv expo-constants在根项目中创建.env文件
API_URL=https://api.example.org
API_TOKEN=abc123忽略.env文件中的.gitignore
在根项目中创建或更新文件app.config.ts,用于导出环境vars和用于ts类型的接口(如https://docs.expo.dev/guides/environment-variables/)。
import 'dotenv/config';
export interface AppConfig {
API_URL: string,
API_TOKEN: string,
}
export default {
name: 'CoolApp',
version: '1.0.0',
extra: {
API_URL: process.env.API_URL,
API_TOKEN: process.env.API_TOKEN,
},
};创建一个将所有环境vars导出到其他文件的config.ts文件
import Constants from 'expo-constants';
import { AppConfig } from '../../app.config';
const { API_TOKEN, API_URL } = Constants.manifest?.extra as AppConfig;https://stackoverflow.com/questions/72544325
复制相似问题