You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native Expo项目绝对导入失效问题求助

解决React Native Expo中绝对导入失效问题

问题现象

代码可正常编译,VSCode的TypeScript能识别~/开头的绝对导入,但Expo运行应用时出现模块解析错误:

Unable to resolve module ~/redux/hooks from ... ~/redux/hooks could not be found within the project or in these directories:
  node_modules

导入示例

import { useAppDispatch, useAppSelector } from '~/redux/hooks'
import * as walletActions from '~/redux/wallet/actions'
import { actions, selectState as selectWalletState } from '~/redux/wallet/slice'
import { multichain } from '~/services/multichain'
import { config } from '~/settings/config'

当前配置

tsconfig.json

"compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "~/*": ["./src/*"]
    },
    ...
}

babel.config.js

module.exports = function (api) {
  api.cache(true)
  return {
    presets: ['babel-preset-expo'],
    plugins: [
      ['react-native-reanimated/plugin'],
      [
        'module:react-native-dotenv',
        {
          envName: 'APP_ENV',
          moduleName: '@env',
          path: '.env',
        },
      ],
      [
        'module-resolver',
        {
          alias: {
            '~/': './src/',
          },
        },
      ],
    ],
  }
}

解决方案

1. 修正babel-plugin-module-resolver的别名配置

babel.config.js中module-resolver的别名配置存在尾斜杠匹配问题,将'~/': './src/'改为'~': './src':

[
  'module-resolver',
  {
    alias: {
      '~': './src',
    },
  },
]

原因:当别名带尾斜杠时,~/redux/hooks会被解析为./src//redux/hooks(多了一层斜杠),导致路径匹配失败;去掉尾斜杠后,~/redux/hooks会正确映射到./src/redux/hooks。

2. 确认babel-plugin-module-resolver已安装

如果尚未安装依赖,执行以下命令:

# npm
npm install --save-dev babel-plugin-module-resolver

# yarn
yarn add -D babel-plugin-module-resolver

3. 清除Expo缓存并重启项目

Expo的缓存可能导致新配置不生效,执行缓存清除命令后重启:

expo r -c

完成以上步骤后,重新运行项目即可正常解析~/开头的绝对导入。

内容的提问来源于stack exchange,提问作者maxspiri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 21:55:30