javascript React-Native 的本地 require() 路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30040534/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 11:32:51  来源:igfitidea点击:

Local require() paths for React-Native

javascriptreactjsreact-native

提问by hoodsy

I am looking for a convenient way to access files in the root of my application while avoiding require() strings that look like:

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

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

There are some good solutions out there for Node (https://gist.github.com/branneman/8048520) but I haven't seen a way to use global variables in React Native.

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

Does anyone have a clean solution to this problem?

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

回答by Tiagojdferreira

From Marc Shilling's answer on https://github.com/facebook/react-native/issues/3099

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

You can use an absolute path on imports/requires:

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

where 'MyApp' is whatever name you registered in your index.ios.js file

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

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

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

Note for VS Code: This works, but be warned that you might lose intellisense and cmd/ctrl + click. Thanks Johan for the info about CS code

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

回答by Anil

You can mark a directory as a package by adding a package.jsonwithin the root directory you want to resolve.

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

e.g:

例如:

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

package.jsonshould look like this:

package.json应该是这样的:

{ "name": "app" }

Restart your packager

react-native start --reset-cache

重启你的打包程序

react-native start --reset-cache

Now you can use the following in all of you project files:

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

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

You can use this same method across other directories in your project, I don't think this works via require, although image paths seemed work.

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



As noted in the comments, you may lose auto-complete in your editor (VSCode).

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

For Jetbrains IDE's there are some ongoing tickets here:

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

This might help with Jetbrains IDE's in the meantime.

同时,这可能有助于 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

回答by DoanND

Put code below on top of your myModulefile:

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

/**
 * @providesModule myModule
 */

Then you can use require('myModule')in any other files.

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

回答by pedro.goes

Complementing @Tiagojdferreira

补充@Tiagojdferreira

You can use his solution with babel-plugin-module-resolver library.

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

Install with:

安装:

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

Configure .babelrc adding plugins property like this:

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

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

Usage:

用法:

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

Hope this helps!

希望这可以帮助!

回答by deanmcpherson

You can use global variables in react native, same as node, properties defined on global are accessible globally.

您可以在 react native 中使用全局变量,与节点相同,定义在 global 上的属性可以全局访问。

e.g.

例如

global.foo = "blah";
console.log(foo); //logs "blah"

Most of the node solutions in the gist above should work correctly.

上面要点中的大多数节点解决方案应该可以正常工作。

One I've used in the past is defining a global function at the top directory level, usually on the first line like

我过去使用的一个是在顶级目录级别定义一个全局函数,通常在第一行,如

global.rootRequire = function(path) { return require(path); }

Which simply allows deeply nested requires to be from the root, and avoids all of the ../../business.

这只是允许深度嵌套的需求来自根,并避免所有../../业务。

However the other comment is true, if this is really an issue, there is probably something structurally deficient with the project.

然而,另一条评论是正确的,如果这真的是一个问题,那么该项目可能存在结构上的缺陷。