我们在`react-native`中使用`babel-plugin-root-import`,一般是`yarn add babel-plugin-root-import@6.6.0`,然后在`.babelrc`配置:
{
"plugins": [
[
"babel-plugin-root-import",
{
"rootPathPrefix": "@",
"rootPathSuffix": "src/"
}
]
]
}
但是我们需要注意,不能在`rootPathPrefix`中设置为`@`,这样很容易跟第三方的依赖产生冲突,比如`import { NavigationContainer } from '@react-navigation/native';`。`'@react-navigation/native'`应该是从`node_modules`中引入,但是这个时候将会从`src`中引入,所以我们需要配置为:
{
"plugins": [
[
"babel-plugin-root-import",
{
"rootPathPrefix": "@src", // 不能用@,因为和其他依赖库产生了冲突
"rootPathSuffix": "src/"
}
]
]
}
在使用`babel-plugin-root-import`时,将`rootPathPrefix`设为`@`可能导致与第三方库如`@react-navigation/native`的导入冲突。为了避免这种问题,应将`rootPathPrefix`改为`@src`,确保模块从`src`目录导入而非`node_modules`。这样可以避免路径混淆,保证项目正常运行。
893

被折叠的 条评论
为什么被折叠?



