【问题标题】:react-native, jest, ts-jest: ReferenceError: React is not definedreact-native, jest, ts-jest: ReferenceError: React is not defined
【发布时间】:2019-12-02 13:33:33
【问题描述】:

我已经苦苦挣扎了几天,以通过 expo + typescript + jest + ts-jest 运行简单的 react-native 测试。 我已经问过一个相关的问题here 这是我的项目的设置:

  1. tsconfig.json
    {
      "compilerOptions": {
        "noEmit": true,
        "lib": ["dom", "esnext"],
        "jsx": "react-native",
        "moduleResolution": "node",
        "allowSyntheticDefaultImports": true,
        "skipLibCheck": true
      }
    }
  1. babel.config.json
module.exports = function(api) {
  api.cache(true);
  return {
    presets: ["babel-preset-expo"]
  };
};
  1. jest.config.js(见official github setting of react-native + ts-jest
const { defaults: tsjPreset } = require("ts-jest/presets");
module.exports = {
  ...tsjPreset,
  preset: "react-native",
  transform: {
    ...tsjPreset.transform,
    "\\.js$": "<rootDir>/node_modules/react-native/jest/preprocessor.js"
  },
  globals: {
    "ts-jest": {
      babelConfig: true
    }
  },
  cacheDirectory: ".jest/cache"
};

我收到此错误

ReferenceError: React is not defined

因为我在我的文件中导入了这样的反应: import React from 'react'

如果我像 import * as React from 'react' 这样导入 它有效。

任何帮助将不胜感激,因为我已经在这个项目中花费了几天时间。

【问题讨论】:

  • 这个有什么锁吗?

标签: react-native jestjs expo ts-jest


【解决方案1】:

我遇到了完全相同的问题,并通过更改我的 tsconfig.json 来解决它

{
  "compilerOptions": {
    /* Basic Options */
    "target": "esnext" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */,
    "module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */,
    "lib": [
      "es6"
    ] /* Specify library files to be included in the compilation. */,
  ...
  }
}

{
  "compilerOptions": {
    /* Basic Options */
    "target": "es2017" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */,
    "module": "ESNext" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */,
    "lib": [
      "es2017"
    ] /* Specify library files to be included in the compilation. */,
  ...
  }
}

【讨论】:

  • 这个解决方案对我有用(expo sdk39)。任何解释为什么?
  • 你拯救了我的一天!谢谢兄弟!
猜你喜欢
  • 2020-06-14
  • 1970-01-01
  • 2021-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-22
  • 1970-01-01
  • 2021-09-14
相关资源
最近更新 更多