【发布时间】:2019-10-03 13:32:16
【问题描述】:
我有一个新的带有 TypeScript 的 React Native 0.61.1 项目。它曾经完美地显示新项目的欢迎屏幕。我添加了一个类,尝试导入它(它甚至自动完成),但它说找不到该组件。
这是我的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重命名截图后,所以这不是问题)包含一个带有渲染方法的简单组件类,默认导出。
这是我的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/screens/OnboardingScreen'?? -
@hongdevelop 刚刚尝试过,显然它是这样工作的。但我不想使用相对路径,我想在应用程序内的任何位置将其用作
views/screens/OnboardingScreen。 -
尝试在 tsconfig.json 文件中将
"baseUrl": "src"替换为"baseUrl": ".", -
@AbhaySharma 但我的基本 URL 不是 root,它是
src???? -
你弄明白了吗?我想使用绝对导入
标签: javascript typescript react-native node-modules metro-bundler