Yefimchuk
Yefimchuk

Reputation: 77

react-native-dotenv Unable to resolve module @env

I'm setting up this lib for TypeScript like here

my env:

API_KEY=someKey..

i'm setting up type/env.d.ts:

declare module '@env' {
    export const API_KEY: string;
}

my babel.config.ts:

   module.exports = function (api) {
    api.cache(true);
    return {
        presets: ["babel-preset-expo"],
        plugins: [
            [
                "module:react-native-dotenv",
                {
                    moduleName: "@env",
                    path: ".env",
                },
            ],
        ],
    };
};

my 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"
  },

and this file where i use 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;

and i get this in the console:

    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};

enter image description here

please help :( I don't know what to do, I've looked all over the internet. maybe my dependencies don't have the up-to-date version of something

ATTENTION when i change my module from @env to 'react-native-dotenv' i'm still get error but some other:

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) {

enter image description here

i hope anyone help me, thanks :)

Upvotes: 4

Views: 12952

Answers (4)

Nizar Bouali
Nizar Bouali

Reputation: 11

In my case I'm using ts and the I fixed the issue by:

  • Creating file env.d.ts
  • Declare my variables: declare module "@env" { export const TEST: string; }

Upvotes: 0

Andrew Einhorn
Andrew Einhorn

Reputation: 1133

Oh man, I battled with this problem for so long, but finally got it to work. These were the steps I took.

  1. Sort out the typescript error by running npx expo install @types/react-native-dotenv -- --dev (Note: if you're using npm instead of yarn, use -- --save-dev instead of -- --dev)

  2. Stop the bundler, then restart and clear the cache with npx expo start --clear

  3. Add "@env": ["node_modules/react-native-dotenv"] to your compiler options paths in tsconfig.json to help expo find the module:

{
  "extends": "expo/tsconfig.base",
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "src/*": ["src/*"],
      "root/*":["./*"],
      "@env": ["node_modules/react-native-dotenv"]
    }
  },
}

Upvotes: 0

Isuru Sandamal
Isuru Sandamal

Reputation: 536

Follow this steps and issue will be resolved.

  1. Clear watchman watches: watchman watch-del-all
  2. Delete node_modules: rm -rf node_modules and run yarn install
  3. Reset Metro's cache: yarn start --reset-cache
  4. Remove the cache: rm -rf /tmp/metro-*

Upvotes: 1

Edgar Olivar
Edgar Olivar

Reputation: 1975

the fs problem is about that module do not exist in the mobile bundle, i had the same issue and i review a few pages about this project, but i not found answer, maybe this can be helpful, i was re-configurate my environment config,

Dependencies:

yarn add dotenv react-native-dotenv expo-constants

Create .env file in root project

API_URL=https://api.example.org
API_TOKEN=abc123

Ignore .env file in .gitignore

Create or update a file app.config.ts in your root project, that export environments vars and the interface for ts typing (like 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,
  },
};

Create a config.ts file that export all environment vars to other files

    import Constants from 'expo-constants';
    import { AppConfig } from '../../app.config';
    
    const { API_TOKEN, API_URL } = Constants.manifest?.extra as AppConfig;

Upvotes: 4

Related Questions