在使用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');

最新文章

  1. kd树和knn算法的c语言实现
  2. [No000023]为何没有更多人从事程序员的工作?程序员常有,优秀程序员不常有!
  3. Hmmer安装与使用
  4. cf.301.D. Bad Luck Island(dp + probabilities)
  5. codeforces Gym 100187J J. Deck Shuffling dfs
  6. jq 换图片路径
  7. Reporting Service 报表报 rsReportServerDatabaseError 错的解决方法
  8. Fragment 整个生命周期
  9. USB otg 学习笔记
  10. POJ 3522 Slim Span
  11. 模拟jquery链式访问
  12. java面试题之int和Integer的区别
  13. js添加删除元素内容
  14. JavaScript观察者模式
  15. 初识ajax
  16. python 全栈开发,Day4(正式)
  17. 解决nginx下connect() to 127.0.0.1:3000 failed (13: Permission denied) while connecting to upstream, client: 127.0.0.1, server: 错误信息
  18. 【转】具透 | 你可能不知道,iOS 10 有一个中国「特供」的联网权限功能
  19. Date ——日期型函数Date常用API
  20. django通用视图(类方法)

热门文章

  1. Spring Boot 2.X(十七):应用监控之 Spring Boot Admin 使用及配置
  2. beacon帧字段结构最全总结(一)——beacon基本结构
  3. 爬虫--requests爬取猫眼电影排行榜
  4. 一条查询语句在MySQL中是如何执行的?
  5. 关于Jvm的见解(二)
  6. XML解析之Jsoup
  7. Nginx使用反向代理实现负载均衡
  8. ffmpeg 编译安装
  9. 【Leetcode 做题学算法周刊】第四期
  10. gopls替换hover文档