【React-Native】优雅的使用 babel 插件配置路径别名

前言

相信前端开发对于 import 一定都不陌生,比如:

import test from '../../../components/test.js'

总是要写上不太优雅的冗余路径,看起来不优雅。

配置别名

我们可以用到 babel-plugin-root-import 这个插件:

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

然后在配置文件 babel.config.js 中进行配置:

module.exports = {
  presets: ["module:metro-react-native-babel-preset"],
  plugins: [
    [
      "babel-plugin-root-import",
      {
        rootPathSuffix: "src",
      },
    ],
  ],
  env: {
    production: {
      plugins: [
        [
          "babel-plugin-root-import",
          {
            rootPathSuffix: "src",
          },
        ],
      ],
    },
  },
};

通过 rootPathSuffix 来匹配给需要的路径起别名,默认别名是 ~

如果另有需要,可以用 rootPathPrefix 来自行修改,比如想用 @root 来替代 src 根目录,如下:

...
      {
      	rootPathPrefix: "@root",
        rootPathSuffix: "src",
      },
...

然后!!!切记要执行如下命令,清除下 watchmannpm 的缓存:

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

然后,本文开头的引用就可以改为:

// import test from '../../../components/test.js'
import test from '~/components/test.js'

看起来是不是优雅多了?

让编辑器能自动跳转

配置了别名,你会发现点击,无法跳转到指定文件。

别担心,在根目录增加一个 jsconfig.json 文件,对于你起别名的目录,在 paths 里面进行配置即可:

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "~/*": ["src/*"]
    },
    "target": "ES6",
    "module": "commonjs",
    "allowSyntheticDefaultImports": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules"]
}

然后,对于 VSCode,就可以直接使用了。 Webstorm 需要做下配置:

【Preferences】 => 【Language & Frameworks】 => 【Webpack】中,选择刚才创建的 jsconfig.json 文件即可。
在这里插入图片描述
然后,我们就可以优雅的开发了~

GitHub Demo 地址

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值