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

我正在使用babel-plugin-module-resolver通过自定义别名轻松导入项目文件。在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文件夹,在该文件夹中有2个文件。

index.tsx:

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

Test.tsx:

import React from 'react';
import {View,Text} from 'react-native';

export default () => {
  return (
    <View>
      <Text>Hello world</Text>
    </View>
  );
};

我只是从Test.tsx内部重新导出Test组件,并在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导入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确实被忽略了。创建了无效的配置,该配置继续工作。

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

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

本文链接:https://www.f2er.com/3160724.html

大家都在问