在React Native项目中找不到模块或其对应的类型声明

问题描述 投票:0回答:2

我正在尝试在 React Native 中包含我的项目的路径别名。 事实上,当我启动应用程序时,它正在工作,所以我认为我的

babel.config.js
没问题,但在 VSCode 中仍然出现错误告诉
Cannot find module or its corresponding type declarations
,所以我认为我的
tsconfig.json
错了

babel.config.js

module.exports = {
  presets: ['module:metro-react-native-babel-preset'],
  plugins: [
    [
      'module-resolver',
      {
        root: ['.'],
        alias: {
          '@ali/assets': './src/assets',
          '@ali/components': './src/components',
          '@ali/colors': './src/theme/colors.ts'
        }
      }
    ]
  ]
}

tsconfig.json

{
  "compilerOptions": {
    "target": "esnext",
    "module": "commonjs",
    "lib": ["es2017"],
    "allowJs": true,
    "jsx": "react-native",
    "noEmit": true,
    "isolatedModules": true,
    "strict": true,
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "skipLibCheck": false,
    "rootDir": ".",
    "paths": {
      "@ali/assets": ["./src/assets/*"],
      "@ali/components": ["./src/components/*"],
      "@ali/colors": ["./src/theme/colors"]
    }
  },
  "exclude": ["node_modules", "babel.config.js", "metro.config.js", "jest.config.js"],
  "extends": "expo/tsconfig.base"
}

这是我的文件 src/screens/Login/index.tsx

import Wellcome from '@ali/components/LogIn/Wellcome'
import React from 'react'

import LoginForm from '../../components/forms/LoginForm'

export const LogIn = () => {
  return (
    <>
      <Wellcome />
      <LoginForm />
    </>
  )
}

export default LogIn

我可以在我的应用程序中看到我的组件 Wellcome,但在 VSCode 中仍然出现错误。

react-native babeljs tsconfig
2个回答
4
投票

这是由于

tsconfig.json
错误的配置造成的。

您应该添加

baseUrl
并删除开头的“.”从路径路线。

试试这个:

   "baseUrl": ".",
   "paths": {
      "@ali/assets/*": ["src/assets/*"],
      "@ali/components/*": ["src/components/*"],
      "@ali/colors/*": ["src/theme/colors"]
    }

0
投票

tsconfig 选项顺序很重要,尝试替换 noEmit 之后的路径并添加 baseUrl

{
  "compilerOptions": {
    "target": "esnext",
    "module": "commonjs",
    "lib": ["es2017"],
    "allowJs": true,
    "jsx": "react-native",
    "noEmit": true,
    "baseUrl": ".",
    "paths": {
      "@ali/assets": ["./src/assets/*"],
      "@ali/components": ["./src/components/*"],
      "@ali/colors": ["./src/theme/colors"]
    }
    "isolatedModules": true,
    "strict": true,
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "skipLibCheck": false,
    "rootDir": ".",
  },
  "exclude": ["node_modules", "babel.config.js", "metro.config.js", "jest.config.js"],
  "extends": "expo/tsconfig.base"
}

我希望这对你有用

© www.soinside.com 2019 - 2024. All rights reserved.