无法导入具有Babel自定义别名的TypeScript组件



我正在使用babel插件模块解析器,使用自定义别名轻松导入项目文件。TypeScript方面似乎一切都很好。下面是tsconfig.json:

{
"compilerOptions": {
/* Basic Options */
"target": "esnext",
"module": "commonjs",
"lib": ["es6"],
"allowJs": true,
"jsx": "react-native",
"noEmit": true,
"isolatedModules": true,
/* Strict Type-Checking Options */
"strict": true,
"noImplicitAny": false,
/* Module Resolution Options */
"moduleResolution": "node",
"baseUrl": ".",
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
/* Experimental Options */
"experimentalDecorators": true
},
"exclude": [
"node_modules", "babel.config.js", "metro.config.js", "jest.config.js"
]
}

我在项目的根文件夹中有一个components文件夹,文件夹中有两个文件。

index.tsx:

export {default as TestComponent } from './Test';

测试.tsx:

import React from 'react';
import {View, Text} from 'react-native';
export default () => {
return (
<View>
<Text>Hello world</Text>
</View>
);
};

我只是从Test.tsx内部重新导出测试组件,并在App.tsx中使用它,如下所示:

import React from 'react';
import {StyleSheet} from 'react-native';
import {TestComponent} from 'components';
const App = () => {
return <>
<TestComponent />
</>;
};
const styles = StyleSheet.create({});
export default App;

我没有收到TypeScript编译器的警告和错误,但当我运行应用程序时,我得到:

Error: Unable to resolve module 'components' from 'App.tsx': components could not be found in the project.

看起来babel的配置是这样的:

module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: [
[
'module-resolver',
{
root: ['./'],
extensions: ['.ios.js', '.android.js', '.js', '.ts', '.tsx', '.json'],
alias: {
"components": "./components"
},
},
],
],
};

有趣的是,如果我从/components/Test导入测试组件,跳过index.tsx中的重新导出,一切都像一个魅力:

import React from 'react';
import {StyleSheet} from 'react-native';
import TestComponent from 'components/Test';
const App = () => {
return <>
<TestComponent />
</>;
};
const styles = StyleSheet.create({});
export default App;

所以我真的不知道这里出了什么问题。有什么想法吗?

我使用的是React Native 0.61.3,所有软件包都是最新版本。

编辑:而且我刚刚发现babel.config.js真的被忽略了。创建了一个无效的配置,该配置仍然有效。

如果您或其他任何人仍然存在此问题,则babel.config.js似乎被忽略了。但实际上它只是被缓存。对我有效的是执行命令npm start --reset-cache。当时,它为我接受了自定义解析器。这很痛苦。

最新更新