React-Native 相对项目路径导入组件

先来看下效果

一般来说

import HomePage from '../../pages/Home/HomePage'                                                      
const ScreenWidth = require('../../config.js');    

修改之后

import HomePage from '~/pages/Home/HomePage'                                                      
const ScreenWidth = require('~/config.js');   

组件安装

npm 执行

npm install babel-plugin-root-import --save-dev

yarn 执行

yarn add babel-plugin-root-import --dev

配置文件

在项目根目录下创建一个.babelrc文件,并添加一下代码:

{
    "plugins": [
        [
            "babel-plugin-root-import",
            { 
              "rootPathSuffix": "./src/",
              "rootPathPrefix": "~"     
            }
        ]
    ]
}
/*
rootPathSuffix 是把src作为根目录,也可设置其他文件夹作为根目录
rootPathPrefix 不设置的话默认为 ~ , 也可自定义
*/

其他的一些用法

{  
"plugins":[
            "babel-plugin-root-import",
            {
                "paths":[
                    {  
                        "rootPathPrefix": "~", // `~` 默认  
                        "rootPathSuffix": "./src/"  
                    },
                    {  
                        "rootPathPrefix": "@", 
                        "rootPathSuffix": "./src/pages/Home/"  
                    }
                ]
            }
            
        ]
}  
  
// 然后你就可以这样使用插件了。  
import HomePage from '~/pages/Home/HomePage';  
import HomePage from '@/HomePage';  

你可能感兴趣的:(React-Native 相对项目路径导入组件)