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

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

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

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

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

安装插件

这里我选用 babel-plugin-root-import 插件,主要是方便,不需要再为了 eslint 不识别 ‘@’ 而增加配置。
这个babel-plugin-module-resolver插件,也可以,但是需要处理 eslint 的配置

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

修改babel.config.js

  1. module.exports = {
  2. presets: ['module:metro-react-native-babel-preset'],
  3. plugins: [
  4. ['@babel/plugin-proposal-decorators', { legacy: true }], // mbox
  5. // ['react-native-reanimated/plugin'],
  6. [
  7. 'babel-plugin-root-import',
  8. {
  9. paths: [
  10. {
  11. rootPathSuffix: './src',
  12. rootPathPrefix: '~/', // 使用 ~/ 代替 ./src (~指向的就是src目录)
  13. },
  14. {
  15. rootPathSuffix: './src/utils',
  16. rootPathPrefix: '!/',
  17. },
  18. ],
  19. },
  20. ],
  21. ],
  22. };

修改import路径测试

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

  1. yarn clear-run
  1. "scripts": {
  2. "android": "react-native run-android",
  3. "ios": "react-native run-ios",
  4. "start": "react-native start",
  5. "test": "jest",
  6. "lint": "npx eslint --ext .js,.jsx,.ts,.tsx ./src",
  7. "lint:fix": "npx eslint --fix .",
  8. "check": "lint-staged",
  9. "format": "prettier --write 'src/**/*.js'",
  10. "prettier": "npx prettier --write .",
  11. "prepare": "husky install",
  12. "clear": "yarn cache clean",
  13. "clear-run": "react-native start --reset-cache",
  14. "del": "rimraf node_modules yarn.lock"
  15. },

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

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

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

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

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