项目场景:
运行打包命令报错: app/utils/toastUtils 模块无法被找到
error Unable to resolve module app/utils/toastUtils from .../workspace/xxx/app/navigators/NavigationUtil.ts:
app/utils/toastUtils could not be found within the project or in these directories:
node_modules
../../../node_modules
14 | import * as storage from '../utils/storage'
15 | import NetInfo from '@react-native-community/netinfo'
> 16 | import { ToastNetWorkErr } from 'app/utils/toastUtils'
| ^
17 |
1、根据当前的项目结构,导入路径 app/utils/toastUtils 似乎将 app 当作根目录。React Native 默认不支持直接以 app 为根路径的导入,除非进行了别名配置。
2、前往 app/utils/ 目录下确认 toastUtils.ts(或 .js)文件是存在的
3、检查 tsconfig.json 和 metro.config.js配置,发现在tsconfig文件配置了别名,但是metro.config.js没有配置。
//tsconfig.json
"paths": {
"app/*": ["./app/*"],
"assets/*": ["./assets/*"]
},
原因分析:
在 TypeScript 的 tsconfig.json 配置了路径别名后,React Native 中并不会直接识别 TypeScript 配置的路径别名,需要通过 Babel 和 Metro Bundler 配置来处理路径别名
解决方案:
TypeScript 的 paths 配置只对 TypeScript 编译器(tsc)生效,但 React Native 使用 Babel 和 Metro Bundler 进行打包,因此需要 Babel 来处理路径别名。module-resolver 是 Babel 插件,可以让路径别名在运行时被正确解析。
1. 安装 Babel 插件 module-resolver
运行以下命令安装:
yarn add babel-plugin-module-resolver --dev
2. 更新 babel.config.js 文件
在 Babel 配置中添加 module-resolver 插件,确保与 tsconfig.json 的路径别名一致:
//babel.config.js
const plugins = [
'@babel/plugin-proposal-export-namespace-from',
/** 添加 module-resolver 进行路径别名解析 */
[
'module-resolver',
{
root: ['./'],
alias: {
app: './app',
assets: './assets',
},
},
],
]
/** @type {import('@babel/core').TransformOptions} */
module.exports = function (api) {
api.cache(true)
return {
presets: ['babel-preset-expo'],
env: {
production: {},
},
plugins,
}
}
3. 重启 Metro Bundler 并清理缓存
运行以下命令,确保新的 Babel 配置生效:
npx react-native start --reset-cache
4. 验证路径别名配置
路径别名设置完成后,你可以这样导入文件:
import { ToastNetWorkErr } from 'app/utils/toastUtils';
import logo from 'assets/images/logo.png';