如何在 Expo 和 React Native 中使用带绝对路径的导入?

How to use import with absolute paths with Expo and React Native?

我正在尝试使用绝对导入路径而不是 Expo 和 React Native 的相对路径。

我查看了 expo 文档但找不到答案...在 React 社区中搜索主题我发现 babel-plugin-module-resolver 但似乎 Expo 已经在使用它所以我改变了我的.babelrc 创建一些别名:

{
  "presets": ["babel-preset-expo"],
  "env": {
    "development": {
      "plugins": [
        "transform-react-jsx-source",
        ["module-resolver", {
          "root": ["./app"],
          "alias": {
            "Components": "./app/components",
          }
        }]
      ]
    }
  }
}

但是我得到了以下错误:

Unable to resolve module '@expo/vector-icons/glyphmaps/Entypo.json' 
from '/Users/eduardoleal/Code/lua/rook/node_modules/@expo/vector-icons/Entypo.js': 
Module does not exist in the module map or in these directories:   /Users/eduardoleal/Code/lua/rook/node_modules/@expo/vector-icons/node_modules/@expo/vector-icons/glyphmaps ,   /Users/eduardoleal/Code/lua/rook/node_modules/@expo/vector-icons/glyphmaps  This might be related to https://github.com/facebook/react-native/issues/4968 To resolve try the following:   
1. Clear watchman watches: 'watchman watch-del-all'.   
2. Delete the 'node_modules' folder: 'rm -rf node_modules && npm install'.   
3. Reset packager cache: 'rm -fr $TMPDIR/react-*' or 'npm start --reset-cache'.
ABI16_0_0RCTFatal -[ABI16_0_0RCTBatchedBridge stopLoadingWithError:] __34-[ABI16_0_0RCTBatchedBridge start]_block_invoke_2 _dispatch_call_block_and_release _dispatch_client_callout _dispatch_main_queue_callback_4CF __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ __CFRunLoopRun CFRunLoopRunSpecific GSEventRunModal UIApplicationMain main start 0x0 

有什么简单的方法可以导入绝对路径吗?

尝试了一段时间后才开始工作。我可以通过以下方式解决问题 .babelrc:

{
  "presets": ["babel-preset-react-native-stage-0/decorator-support"],
  "env": {
    "development": {
      "plugins": ["transform-react-jsx-source"]
    }
  },
  "plugins": [
    ["module-resolver", {
      "alias": {
        "react-native-vector-icons": "@expo/vector-icons",
        "@expo/vector-icons/lib/create-icon-set": "react-native-vector-icons/lib/create-icon-set",
        "@expo/vector-icons/lib/icon-button": "react-native-vector-icons/lib/icon-button",
        "@expo/vector-icons/lib/create-icon-set-from-fontello": "react-native-vector-icons/lib/create-icon-set-from-fontello",
        "@expo/vector-icons/lib/create-icon-set-from-icomoon": "react-native-vector-icons/lib/create-icon-set-from-icomoon",
        "@expo/vector-icons/lib/icon-button": "react-native-vector-icons/lib/icon-button",
        "@expo/vector-icons/glyphmaps": "react-native-vector-icons/glyphmaps",
        "$components": "./app/components",
        "$config": "./app/config",
        "$helpers": "./app/helpers",
        "$navigators": "./app/navigators",
        "$reducers": "./app/reducers",
        "$screens": "./app/screens",
        "$images": "./assets/images",
        "$fonts": "./assets/fonts",
        "$icons": "./assets/icons",
        "$videos": "./assets/videos",
      }
    }]
  ]
}

我把babel-preset-expo的内容复制到我的.babelrc。这不是最好的解决方案...但它可以正常工作。

更多详情here

Just simple 让你的 .babelrc 像这样简单:

{
  "presets": ["babel-preset-expo"],
  "env": {
    "development": {
      "plugins": ["transform-react-jsx-source"]
    }
  }
}

然后像这样导入:

import Entypo from '@expo/vector-icons/Entypo';

Update: Expo v32.0.0 and up

Expo init 正在为您创建 babel.config.js。只需将 plugins 键添加到您的 babel.config.js 文件并添加您的别名。不再需要 env 密钥。

module.exports = function(api) {
  api.cache(true)

  return {
    presets: ['babel-preset-expo'],
    plugins: [
      [
        'module-resolver',
        {
          alias: {
            assets: './assets',
            components: './src/components',
            modules: './src/modules',
            lib: './src/lib',
            types: './src/types',
            constants: './src/constants',
          },
        },
      ],
    ],
  }
}

Update: Changes for Expo.io SDK v20.0.0

从 SDK v20.0.0 开始,您可以使用正常的 Babel Expo 预设

{
  "presets": ["babel-preset-expo"],
  "env": {
    "development": {
      "plugins": ["transform-react-jsx-source"]
    }
  },
  "plugins": [
    ["module-resolver", {
      "alias": {
        "alias-name": "./app",
      }
    }]
  ]
}

Expo.io SDK v19.0.0 and before

没有 root 元素,分隔 plugins 并将 presets 更改为 babel-preset-react-native-stage-0/decorator-support,别名对我有用。

在版本 16.0.0 上使用 Expo.io
在 Expo 论坛中找到这个:https://forums.expo.io/t/relative-paths-with-expo/654/3

你能证实这对你的情况也有效吗?

{
  "presets": ["babel-preset-react-native-stage-0/decorator-support"],
  "env": {
    "development": {
      "plugins": ["transform-react-jsx-source"]
    }
  },
  "plugins": [
    ["module-resolver", {
      "alias": {
        "alias-name": "./app",
      }
    }]
  ]
}

对于最新的 expo 用户(sdk 版本 >= 32)。

只需在您的 babel.config.js 中添加 plugins 属性(在项目根目录中找到此文件)。

module.exports = function (api) {
  api.cache(true);
  return {
    presets: ['babel-preset-expo'],
    plugins: [
      [
        'module-resolver',
        {
          alias: {
            'alias-name': './src/assets/bla/bla',
          },
        },
      ],
    ],
  };
};
./src
 |- package.json
 |- Bar/
 |   `- index.js
 `- Foo.js

package.json

{
  "name": "~" // whatever u want
}

然后

import { Foo } from "~/Foo";
import { Bar } from "~/Bar";
// ...

此外 以防有人遇到与 Typescript 相同的问题。

如果您使用的是 Typescript,您还需要将其添加到 tsconfig

"compilerOptions": {
  ...
  "baseUrl": ".",
  "paths": {
    "@src/*": ["./src/*"],
    "@assets/*": ["./assets/*"]
  }
},

这是我的配置 babel.config

plugins: [
  ...
  [
    "module-resolver",
    {
      alias: {
        "@assets": "./assets",
        "@src": "./src",
      },
    },
  ],
],