我们在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/"
}
]
]
}