React-Native 的本地 require() 路径

IT技术 javascript reactjs react-native
2021-05-20 12:29:15

我正在寻找一种方便的方法来访问我的应用程序根目录中的文件,同时避免如下所示的 require() 字符串:

require('../../../../myModule')

Node ( https://gist.github.com/branneman/8048520 )有一些很好的解决方案,但我还没有看到在 React Native 中使用全局变量的方法。

有没有人对这个问题有一个干净的解决方案?

4个回答

来自 Marc Shilling 在https://github.com/facebook/react-native/issues/3099上的回答

您可以在导入/要求上使用绝对路径:

import {ProximaNovaText} from 'MyApp/src/components'; require('MyApp/src/utils/moment-twitter');

其中“MyApp”是您在 index.ios.js 文件中注册的任何名称

VS Code 的注意事项:这有效,但请注意,您可能会丢失智能感知和 cmd/ctrl + 单击。感谢 Johan 提供有关 CS 代码的信息

您可以通过package.json在要解析的根目录中添加 将目录标记为包

例如:

- app
    - package.json     // ← Add this package.json file
    - config
    - components
    - ... (etc)

package.json 应该是这样的:

{ "name": "app" }

重启你的打包程序

react-native start --reset-cache

现在您可以在所有项目文件中使用以下内容:

import store from 'app/config/store';
import Button from 'app/components/Button';

您可以在项目中的其他目录中使用相同的方法,我认为这不会通过require,尽管图像路径似乎有效。


如评论中所述,您可能会在编辑器 (VSCode) 中失去自动完成功能。

对于 Jetbrains IDE,这里有一些正在进行的票证:

同时,这可能有助于 Jetbrains IDE。

// A slash may allow auto-complete to work in your IDE (but will fail to resolve)
import Button from '/app/components/Button'; // Cannot be resolved

将以下代码放在myModule文件顶部

/**
 * @providesModule myModule
 */

然后您可以require('myModule')在任何其他文件中使用。

补充@Tiagojdferreira

您可以将他的解决方案与 babel-plugin-module-resolver 库一起使用。

安装:

npm install --save-dev babel-plugin-module-resolver

像这样配置 .babelrc 添加插件属性:

{
  "presets": ["react-native"],
  "plugins": [
    ["module-resolver", {
      "alias": {
        "@src": "MyApp/src",
        "@otherAlias": "MyApp/src/other/path",
      }
    }]
  ]
}

用法:

require('@src/utils/moment-twitter');

希望这可以帮助!