我不完全确定为什么会收到此错误,因为 node_modules
中存在 react 并导入到引用文件中
引用的App.js
文件就是这个
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const react_1 = __importDefault(require("react"));
const unstated_1 = require("unstated");
const layouts_1 = __importDefault(require("./layouts"));
const App = () => (<unstated_1.Provider>
<layouts_1.default />
</unstated_1.Provider>);
exports.default = App;
这是 TypeScript 的输出 ^。非转译版如下
import React from 'react'
import { Provider as StateProvider } from 'unstated'
import AppRoot from './layouts'
const App = () => (
<StateProvider>
<AppRoot />
</StateProvider>
)
export default App
我的项目结构是这样的
packages/
native-app/
node_modules/
ios
index.js
src/
App.tsx
dist/
native-app/
src/
App.js
server/
server/
我觉得这可能与嵌套在 dist 文件夹中有关?我的主要 react native index.js
像这样导入 App
import { AppRegistry } from 'react-native'
import App from './dist/native-app/src/App'
AppRegistry.registerComponent('MyApp', () => App)
注意:这看起来像 monorepo,但我没有使用 yarn workspaces 或 lerna 之类的东西,包安装在每个文件夹中,即 native-app
和 server
以及一些常见的 devDependencies
,如 typescript、tslint 和 prettier 安装在 packages
所在的根文件夹中。
项目使用以下tsconfig
{
"compilerOptions": {
"target": "es2017",
"module": "commonjs",
"lib": ["es2017"],
"removeComments": true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"skipLibCheck": true,
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"noImplicitThis": true,
"alwaysStrict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true
},
"exclude": [
"scripts",
"packages/native-app/dist",
"packages/server/functions/dist"
]
}
并为native-app
打包json
{
"name": "skimitar-app",
"version": "1.0.0",
"description": "Skimitar app",
"private": true,
"dependencies": {
"asq-react-native-device": "1.2.2",
"asq-react-native-facebook-log-in": "1.1.0",
"asq-react-native-google-sign-in": "1.2.0",
"asq-react-native-sensors": "1.1.0",
"react": "16.4.2",
"react-native": "0.56.0",
"react-native-firebase": "4.3.8",
"react-native-svg": "6.5.2",
"unstated": "2.1.1"
},
"devDependencies": {
"@types/react": "16.4.13",
"@types/react-native": "0.56.17"
}
}
最佳答案
将 React 与 TypeScript 结合使用时,像这样更改 React 导入语句:
import * as React from 'react';
您还可以将 tsconfig.json 文件中的 module
选项更改为“es2015”:
{
"compilerOptions": {
"module": "es2015",
...
关于reactjs - 引用错误 : Can't find variable React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52253598/