繁体   English   中英

React Native TypeScript:无法解析模块(但它存在)

[英]React Native TypeScript: Unable to resolve module (but it exists)

我有一个新的带有 TypeScript 的 React Native 0.61.1 项目。 它曾经完美地显示新项目的欢迎屏幕。 我添加了一个 class,尝试导入它(它甚至自动完成),但它说找不到该组件。

这是我的tsconfig.json (所有代码都在我的src文件夹中,该文件夹位于我的项目根目录中):

{
    "compilerOptions": {
      // Target latest version of ECMAScript.
      "target": "esnext",
      // Search under node_modules for non-relative imports.
      "moduleResolution": "node",
      // Process & infer types from .js files.
      "allowJs": true,
      // Don't emit; allow Babel to transform files.
      "noEmit": true,
      // Enable strictest settings like strictNullChecks & noImplicitAny.
      "strict": true,
      // Disallow features that require cross-file information for emit.
      "isolatedModules": true,
      // Import non-ES modules as default imports.
      "esModuleInterop": true,
      "baseUrl": "src",
      "jsx": "react-native"
    }
  }

注意那里的baseUrl 在我添加它之前它也不起作用

这是我的项目结构:

在此处输入图像描述

我的OnboardingScreen.tsx (我在截屏后将其从Onboarding.tsx重命名,所以这不是问题)包含一个简单的组件 class 具有渲染方法,默认导出。

这是我的App.tsx

import React from 'react';
import {
  StatusBar,
} from 'react-native';
import OnboardingScreen from 'views/screens/OnboardingScreen';

const App: () => React.ReactNode = () => {
  return (
    <>
      <StatusBar barStyle="dark-content" />
      <OnboardingScreen/>
    </>
  );
};


export default App;

当我键入Onbo...时,它甚至会自行完成导入。 但是当我运行应用程序时,我得到了臭名昭著的错误:

Unable to resolve module `views/screens/OnboardingScreen` from `src/App.tsx`: views/screens/OnboardingScreen could not be found within the project.

If you are sure the module exists, try these steps:
 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-*

在你问之前:是的,每次尝试后我都会执行上述所有操作,甚至重新启动 Vscode。

我还尝试添加以下tsconfig.json

 "paths": {
    "views/*":["src/views/*"]
 }

虽然也没有任何改变。 我究竟做错了什么? (我在 TypeScript 3.6.2)

更新:显然, paths被完全忽略,但如果我将package.json文件放入我想通过导入引用的每个根文件夹(例如components文件夹)中,它就会被拾取。 例如,我将以下package.json放入components中:

{
    "name": "components"
}

然后我的代码可以引用它。 不过,我仍然不知道为什么它不适用于tsconfig path

解决此错误的一种方法是:

views文件夹中添加一个 package.json 文件,内容为: {"name": "@services"}

导入必须是import OnboardingScreen from '@views/screens/OnboardingScreen';

React-native 和 TypeScript 使用单独的方法来查找具有绝对路径的文件。 这种方式为我解决了这个错误:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM