zoukankan      html  css  js  c++  java
  • react-native 相对项目路径导入组件 ___ babel-plugin-root-import

    在使用react-native的时候,经常要自定义很多组件,但是只能使用../../../的方式,经常不记得这是多深,有没有一个插件,能自动帮我们解决这样的问题?

    使用指南

    我们使用的目标要达到以下的使用效果

    // 通常
    import SomeExample from '../../../some/example.js';
    或
    const OtherExample = require('../../../other/example.js');
    
    // 使用了 Babel-Root-Importer 之后
    import SomeExample from '~/some/example.js';
    或
    const OtherExample = require('~/other/example.js');
    

    组件安装

    npm 方式

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

    yarn 方式

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

    配置

    增加一个 .babelrc项目根目录,并写入(如果已有,则加入plugins):

    {
      "plugins": [
        [
          "babel-plugin-root-import"
        ]
      ]
    }
    

    温馨提示

    已有项目,记得清理一个缓存(先关闭所有控制侦听程序)

    watchman watch-del-all
    npm start -- --reset-cache
    

    扩展

    自定义根路径前缀

    如果你想把src/js作为项目根入口,你可以修改.babelrc为以下内容:

    {
      "plugins": [
        [
          "babel-plugin-root-import",
          {
            "rootPathSuffix": "src/js"
          }
        ]
      ]
    }
    

    如何你想修改项目的默认根入口别名,默认~

    {
      "plugins": [
        [
          "babel-plugin-root-import", {
            "rootPathPrefix": "@"
          }
        ]
      ]
    }
    

    也可以定义多组别名入口

    {
      "plugins": [
        ["babel-plugin-root-import", [{
          "rootPathPrefix": "~", // `~` 默认
          "rootPathSuffix": "src/js"
        }, {
          "rootPathPrefix": "@",
          "rootPathSuffix": "other-src/js"
        }, {
          "rootPathPrefix": "#",
          "rootPathSuffix": "../../src/in/parent" //也支持父级路径
        }]]
      ]
    }
    

    // 然后你就可以这样使用插件了。

    import foo from '~/my-file';
    const bar = require('@/my-file');
    
  • 相关阅读:
    Python3 获取抖音无水印视频 2020年12月23日----lanyi原创
    javascript9分享到菜单,菜单在屏幕左侧的移出和收回
    javascript8图片刹车运动
    javascript7图片的淡入淡出
    javascript6鼠标拖拽图片
    javascript5每秒改变字体颜色的大小
    javascript4动态生成表格
    javascript3跟随鼠标的提示框
    javascript2选项卡
    同学,为什么Golang中不用this和self
  • 原文地址:https://www.cnblogs.com/qiqi715/p/9338756.html
Copyright © 2011-2022 走看看