Home > OS >  Cannot find module '@env' from 'src/store.ts' in react expo
Cannot find module '@env' from 'src/store.ts' in react expo

Time:01-08

I am trying to create an expo react app using typescript. The app works perfectly fine but when I am trying to write some tests using Jest, it always says it can not find the module '@env' from my store file.

 Cannot find module '@env' from 'src/store.ts'

    Require stack:
      src/store.ts
      src/screens/HomeScreen.tsx
      src/tests/HomeScreen.test.tsx

    > 1 | import { REACT_APP_API_URL } from '@env';
        | ^
      2 | import axios from 'axios';
      3 | import { Alert } from 'react-native';
      4 | import create from 'zustand';

      at Resolver._throwModNotFoundError (node_modules/jest-resolve/build/resolver.js:425:11)
      at Object.<anonymous> (src/store.ts:1:1)
      at Object.<anonymous> (src/screens/HomeScreen.tsx:5:1)
      at Object.<anonymous> (src/tests/HomeScreen.test.tsx:3:1)

HomeScreen.test.txt

import React from 'react';
import renderer from 'react-test-renderer';
import Home from '../screens/HomeScreen';

describe('<App />', () => {
  it('has 1 child', () => {
    const tree = renderer.create(<Home />).toJSON();
    console.log('test', tree);
  });
});

The @env is defined in a src/types and the file env.d.ts

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

jest.config.js

// jest.config.js
// Sync object
module.exports = {
  preset: 'jest-expo',
  transform: {
    '^. \\.tsx?$': [
      'ts-jest',
      {
        tsconfig: {
          jsx: 'react',
        },
      },
    ],
  },
  testMatch: ['**/?(*.) (spec|test).ts?(x)'],
  collectCoverageFrom: [
    '**/*.{ts,tsx}',
    '!**/coverage/**',
    '!**/node_modules/**',
    '!**/babel.config.js',
    '!**/jest.setup.js',
  ],
  moduleFileExtensions: ['js', 'ts', 'tsx'],
  transformIgnorePatterns: [
    'node_modules/(?!(jest-)?react-native|@react-native|react=native|react-clone-referenced-element|@react-native-community|expo(nent)?|@expo(nent)?/.*|react-navigation|@react-navigation/.*|@unimodules/.*|sentry-expo)',
  ],
  coverageReporters: ['json-summary', 'text', 'lcov'],
  rootDir: './',
  modulePaths: ['<rootDir>'],
  collectCoverage: false,
  moduleNameMapper: {
    '#(.*)': '<rootDir>/node_modules/$1',
  },
};

tsconfig.json

{
  "extends": "expo/tsconfig.base",
  "compilerOptions": {
    "jsx": "react-jsx",
    "strict": true,
    "typeRoots": ["./src/types"],
    "types": ["jest", "node","@types/jest"],
    "baseUrl": ".", // this must be specified if "paths" is specified.
    "paths": {
      "@env": ["node_modules/@env"] // this mapping is relative to "baseUrl"
    },
    
  },
}

babel.config.js

module.exports = function (api) {
  api.cache(true);
  return {
    presets: ['babel-preset-expo'],
    plugins: [
      'react-native-reanimated/plugin',
      [
        'module:react-native-dotenv',
        {
          moduleName: '@env',
          path: '.env',
          blacklist: null,
          whitelist: null,
          safe: false,
          allowUndefined: true,
        },
      ],
    ],
  };
};

I tried mostly everything e.g. Jest cannot find module @env React Native from here and also clear cache and reinstall all but nothing worked. Can someone help me with this?

CodePudding user response:

first you create new folder under your src folder and you call it types, then you create a file named .env.d.js under types. finally you add your env variable

declare module '@env' {
export const REACT_APP_API_URL;
}

CodePudding user response:

  1. Create a types folder in your source folder.

  2. Create a file named env.d.ts in the types folder.

  3. Define your env variables as strings.

    declare module '@env' {
    
      export const REACT_APP_API_URL: string;
    
      // other ones
    }
    
  • Related