首页 > 解决方案 > 开玩笑找不到模块@env React Native

问题描述

我目前遇到了一些问题,我在我的反应原生应用程序https://github.com/goatandsheep/react-native-dotenv中使用它来处理.env。

错误 => 无法从“src/api/api.ts”中找到模块“@env”

我目前正在测试我的 redux 传奇以调用 api 端点:

import axios from 'axios';
import {API_URL} from '@env';

export default axios.create({
  baseURL: API_URL,
  responseType: 'json',
});

API端点

export const sendCheckNumber = async (
  phoneNumber: string,
): Promise<AuthenticationTO> => {
  const response = await axios.get<AuthenticationTO>(
    `SendCheckNumber/${phoneNumber}`,
  );

  return response.data;
};

我正在使用 ts-jest package.json。我在文档中看到它可以在 ts-jest 中包含 bable,因为我正在使用 bable 将“模块:react-native-dotenv”作为插件导入。我认为这已经解决了我的问题,但不幸的是它仍然失败。也许你们中的一些人有一些建议可能导致这个错误。

谢谢!!!

包.json

"jest": {
    "preset": "react-native",
    "transform": {
      "^.+\\.js$": "<rootDir>/node_modules/react-native/jest/preprocessor.js",
      "\\.(ts|tsx)$": "ts-jest"
    },
    "globals": {
      "ts-jest": {
        "babelConfig": "babel.config.js",
        "tsConfig": "tsconfig.jest.json"
      }
    },
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js"
    ],
    "modulePaths": [
      "<rootDir>/src"
    ],
    "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$"
  }

标签: reactjstypescriptreact-nativejestjs

解决方案


我解决了这个问题,如下所示。

import {API_URL} from '@env';`

改为添加:

import {API_URL} from 'react-native-dotenv';

并在babel.config.js中添加下一个

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

这对我来说很有用。


推荐阅读