ReactNative中引入自定义组件通常采用 '../../../xxx'的形式,使用 babel-plugin-root-import 插件,可以达到如下效果
使用前
import List from '../../../components/list
使用后
import '~/components/list
或者
import '@/components/list
npm install babel-plugin-root-import --save-dev
或者
yarn add babel-plugin-root-import --dev
安装完成之后
修改 babel.config.js 文件
修改前
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
};
修改后
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: [
["babel-plugin-root-import",{
"rootPathSuffix": "./src/",
"rootPathPrefix": "@/"
}]
]
};
rootPathSuffix 将src目录设置为根入口
rootPathPrefix src对应的别名(如果不设置,默认为“~”)
注:react-native 版本 0.59.8