React Native项目设置路径别名

发布时间 2023-05-22 16:31:50作者: 甜点cc

没有设置路径别名之前代码是这样的:

import { px2dp } from '../../utils/screenKits';

路径相当冗长,看着就头疼。增加了路径别名之后,变成这样

import { px2dp } from '~/utils/screenKits';

心里清爽多了!
具体操作见下文,实操性强!

安装插件

这里我选用 babel-plugin-root-import插件,主要是方便,不需要再为了 eslint 不识别 '@' 而增加配置。

这个babel-plugin-module-resolver插件,也可以,但是需要处理 eslint 的配置

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

修改babel.config.js

module.exports = {
  presets: ['module:metro-react-native-babel-preset'],
  plugins: [
    ['@babel/plugin-proposal-decorators', { legacy: true }], // mbox
    // ['react-native-reanimated/plugin'],
    [
      'babel-plugin-root-import',
      {
        paths: [
          {
            rootPathSuffix: './src',
            rootPathPrefix: '~/', // 使用 ~/  代替 ./src (~指向的就是src目录)
          },
          {
            rootPathSuffix: './src/utils',
            rootPathPrefix: '!/',
          },
        ],
      },
    ],
  ],
};

修改import路径测试

清除rn缓存并重新启动项目

yarn clear-run
"scripts": {
  "android": "react-native run-android",
  "ios": "react-native run-ios",
  "start": "react-native start",
  "test": "jest",
  "lint": "npx eslint --ext .js,.jsx,.ts,.tsx ./src",
  "lint:fix": "npx eslint --fix .",
  "check": "lint-staged",
  "format": "prettier --write 'src/**/*.js'",
  "prettier": "npx prettier --write .",
  "prepare": "husky install",
  "clear": "yarn cache clean",
  "clear-run": "react-native start --reset-cache",
  "del": "rimraf node_modules yarn.lock"
},

可以看到项目可以正常启动、正常运行

?修复函数跳转到定义功能

配置vscode: https://code.visualstudio.com/docs/languages/jsconfig
再项目根目录增加 jsconfig.json 文件

{
  "compilerOptions": {
    "baseUrl": ".", // 基础目录
    "paths": { //  指定相对于 baseUrl 选项计算的路径映射, 别名路径也可以跳转
      "~/*": [
        "src/*"
      ]
    }
  }
}

这个配置是针对编辑器的,不用重启项目,配置即生效


我是 甜点cc

公众号:【看见另一种可能】