Require cycles are allowed, but can result in uninitialized values. Consider refactoring to remove the need for a cycle - react-native

I am receiving this warning message in my chrome console for my react-native project. Do you have any idea why I am getting this?
This is the complete message:
Require cycle: node_modules/react-native-radio-buttons/lib/index.js ->
node_modules/react-native-radio-buttons/lib/segmented-controls.js ->
node_modules/react-native-radio-buttons/lib/index.js
Require cycles are allowed, but can result in uninitialized values.
Consider refactoring to remove the need for a cycle.
I appreciate any suggestions.
Thanks

TL;DR: You import module A into module B and module B into module A resulting in a cycle A → B → A → B → A ..., which can result in errors. Resolve that by restructuring your modules, so that the cycle breaks.
Detailed Answer
In javascript if you import different modules into other modules all this importing generates a dependency tree:
root_module
┌───────────┴───────────┐
sub_module_A sub_module_B
┌────────┴────────┐
sub_module_C sub_module_D
When you run your code, all modules will be evaluated from bottom to top or from leaves to the trunk, so that for example if you import modules C and D into module B all exports of C and D are already evaluated and not undefined anymore. If module B would be evaluated before C and D, module B would be not working, because all exports from C and D would be undefined, since they have not been evaluated yet.
Still, it can be possible to form cycles in your dependency tree (this is what you got a warning for):
root_module
┌───────────┴───────────┐
sub_module_A sub_module_B
↑ ↓
sub_module_C
Problem: Let's say the evaluation starts now with module C. Since it imports something from module B and it has not been evaluated yet, module C is not working correctly. All imported stuff from B is undefined. This actually is not that bad, since in the end module C is evaluated once again when everything else has been evaluated, so that also C is working. The same goes if evaluation starts with module B.
BUT: If your code relies on a working module C from the very beginning, this will result in very hard to find errors. Therefore you get this error.
How to solve: In your case the warning also gives a detailed explanation, where the cycle emerges. You import native-radio-buttons/lib/segmented-controls.js in node_modules/react-native-radio-buttons/lib/index.js and node_modules/react-native-radio-buttons/lib/index.js in native-radio-buttons/lib/segmented-controls.js. It seems like the cycle is placed inside some of your node modules. In this case there is unfortunately no way you could solve that by yourself.
If the cycle is in your own code, you have to extract some exports into a third module / file, from which you import the code into both modules previously forming the cycle.

You are probably importing something from "file A" into "file B", then importing something again from "file B" into "file A" .
Examine all the imports from both the files and see if there's any such cycle.

To prevent from having to write multiple lines of
import SomeComponent from "../components"
import AnotherComponent from "../components"
import AndAnotherComponent from "../components"
import AndOneMoreComponent from "../components"
I created a comp.js file where I could import the components as they are created and export them as modules.
All components are then able to be reached from one place.
So you can then have something like this in some place...
import { SomeComponent, AnotherComponent, AndAnotherComponent, AndOneMoreComponent} from './comp'
Now what happens in the renderer for example when SomeComponent is rendered....
import * as React from "react";
import { AnotherComponent} from '../comps';
import { View, Text } from "react-native";
function SomeComponent() {
return (
<>
<AnotherComponent />
<View><Text>EXAMPLE OF SOMECOMPONENT</Text></View>
</>
)
}
export default SomeComponent;
In the example, SomeComponent could be called in the main App, and when it renders it also asks for a component from the comp.js
This is what triggers the Require cycle warning because a module that was imported from one place, is then rendering and asking to import another module from the same place it was rendered from.
What are your thoughts on this, should I revert back to using single import statements or do you think there is a danger in using the module export as it is currently setup?

I my case, I have sold the same problem in react-native navgiation.
What I did ?
Already I was using react-navigation like below
export const containerRef = createRef();
function App(){
return (
<NavigationContainer ref={containerRef}>
....
<NavigationContainer>
);
}
and then I was consuming it like:
import {containerRef} from 'filename';
onPress = ()=> containerRef.current.navigate('Chat');
But I updated like below and warning has gone.
function App(){
return (
<NavigationContainer> // removed ref
....
<NavigationContainer>
);
}
and then I was consuming it like:
import { useNavigation } from '#react-navigation/native';
onPress = ()=> useNavigation.navigate('Chat');

This occurs if your code contains cyclic dependencies. If these dependencies exist within your own libraries, you can easily fix them. But if this is happening in 3rd party libraries, you can't do much except waiting for the developers to fix these.
Another reason might be this: Some imports cause this warning if they're done through the require keyword. Replace these with import statements and you might be good to go. For example,
const abc = require("example"); // Don't use this syntax
import abc from "example" // Use this syntax instead
NOTE: This might vary from project to project. For a detailed understanding of require vs import, refer to this link.

In my case the warning was like this;
Require cycle: src\views\TeamVerification.js -> src\components\TeamVerificationListItem.js ->
src\views\TeamVerification.js Require cycles are allowed, but can result in uninitialized values. Consider refactoring to remove the need for a cycle.
As it indicates, TeamVerification was importing TeamVerificationListItem and TeamVerificationListItem was also importing TeamVerification. It was an unused import but after I remove it the warning gone.

As others have already mentioned, for your own packages
Move things required within two modules by each other into a third module
Avoid imports from barrel-files (index.ts/js) or aliases (#mycompany/my-module) if you are within the same "my-module"
What others have not mentioned (and which seems to be the problem for OP), for packages not within your responsibility (eg node_modules from NPM), the only thing you can do is
Disable the warning. It will still show up in metro console, but no more yellow warning snackbar: import { LogBox } from 'react-native'; LogBox.ignoreLogs(['Require cycle: node_modules/']); You can place the code in App.tsx, for example.
Modify the package contents of the node_modules itself and patch the package contents after every npm install via patch-package => I think this is an overkill if the circular imports don't produce actual errors

You should use the Relation wrapper type in relation properties in ES Modules projects to avoid circular dependency issues, just click here: https://typeorm.io/#relations-in-esm-projects

In my case, i had the same warning after the installation of a 'package'
and in their documentation, it was import SomeFunc from 'package'
and instantly the warning showed up
Require cycles are allowed but can result in uninitialized values. Consider refactoring to remove the need for a cycle.
but as soon as I destructure the SomeFunc there was no more warning
import {SomeFunc} from 'package'
please look at the destructuring

I used react-native-maps in my project and I got the same error.
Just upgraded from 0.27.1 -> 0.28.0.
I can confirm that this issue is fixed.
Thank you

if use NavigationContainer in #react-navigation/native
import {createRef} from 'react';
<NavigationContainer ref={createRef()}>

Please check whether you have imported same details within that file.
(i.e)
your file being as a actions/meals.js and you have added the line in the same file like
import { Something } from './actions/meals.js'

Related

UserActions logic is moved to #spartacus/user

Based on this upgrade suggestion I’m trying to import UserActions/UserDetailsAction from #spartacus/user lib but am getting the error has no exported member.
// TODO:Spartacus - UserActions - Following actions 'ForgotPasswordEmailRequestAction', 'ResetPasswordAction', 'EmailActions', 'UpdatePasswordAction', 'UserDetailsAction' were removed. Logic was moved to '#spartacus/user'
Module ‘“#spartacus/user”’ has no exported member ‘UserActions’.
import { UserActions } from '#spartacus/user';
this.store.dispatch(new UserActions.LoadUserDetails(user));
import { UserActions } from '#spartacus/user';
Tried to import UserActions from the user lib
According to the technical changes documentation, you should use the new recommended approach with commands and queries as mentioned in the link. But you can also try importing from #spartacus/user/account, #spartacus/user/profile or #spartacus/core bearing in mind that your previously used actions may not exist anymore.
In case it helps, a similar question was also asked here.
Based on technical changes in Spartacus 4.0, Some branches of the ngrx state for the User feature were removed and logic has been moved to facades in #spartacus/user library.
In your case, instead of dispatching an action, simply use the get method from UserAccountFacade that is part of #spartacus/user.

Python.Net: how to execute modules in packages?

I'm not a Python programmer so apologies if I don't get some of the terminology right (pacakages, modules)!
I have a folder structure that looks something like this:
C:\Test\System\
C:\Test\System\intercepts\
C:\Test\System\intercepts\utils1\
C:\Test\System\intercepts\utils2\
The last three folders each contain an empty __init__.py folder, while the latter two folders (\utils1, \utils2) contain numerous .py modules. For the purposes of my question I'm trying to execute a function within a module called "general.py" that resides in the \utils1 folder.
The first folder (C:\Test\System) contains a file called "entry.py", which imports the .py modules from all those sub-folders:
from intercepts.utils1 import general
from intercepts.utils1 import foobar
from intercepts.utils2 import ...
..etc..
And here is the C# code that executes the above module then attempts to call a function called "startup" in a module called "general.py" in the \utils1 folder:
const string EntryModule = #"C:\Test\System\entry.py";
using (Py.GIL())
{
using (var scope = Py.CreateScope())
{
var code = File.ReadAllText(EntryModule);
var scriptCompiled = PythonEngine.Compile(code, EntryModule);
scope.Execute(scriptCompiled);
dynamic func = scope.Get("general.startup");
func();
}
}
However I get a PythonException on the scope.Execute(...) line, with the following message:
No module named 'intercepts'
File "C:\Test\System\entry.py", line 1, in <module>
from intercepts.utils1 import general
I'm able to do the equivalent of this using IronPython (Python 2.7), so I assume I'm doing something wrong with Python.Net (rather than changes to how packages work in Python 3.x).
I'm using the pythonnet 3.0.0 NuGet package by the way.
Edit
I've tried importing my "entry.py" module as follows:
dynamic os = Py.Import("os");
dynamic sys = Py.Import("sys");
sys.path.append(os.path.dirname(EntryModule));
Py.Import(Path.GetFileNameWithoutExtension(EntryModule));
It now appears to get a little further, however there's a new problem:
In the "entry.py" module you can see that it first imports a module called "general", then a module called "foobar". "foobar.py" contains the line import general.
When I run my C#, the stack trace is now as follows:
No module named 'general'
File "C:\Test\System\intercepts\utils1\foobar.py", line 1, in <module>
import general
File "C:\Test\System\entry.py", line 2, in <module>
from intercepts.utils1 import foobar
Why can't the second imported module ("foobar") "see" the module that was imported immediately before it ("general")? Am I even barking up the right tree by using Py.Import() to solve my original issue?
This turned out to be a change in how Python 3 handles imports, compared to 2, and nothing to do with Python.Net.
In my "foobar.py" module I had to change import general to from . import general. The issue is explained here but I've included the pertinent section below:

ACE editor - allow custom modes and themes in Angular/TypeScript

Introduction:
I've an Angular application where custom SQL statements can be written by using the ACE editor (https://ace.c9.io/). Even though there are modes and themes for SQL, I wanted to create a custom mode and a custom theme for my requirements.
Setup:
I followed this tutorial: https://blog.shhdharmen.me/how-to-setup-ace-editor-in-angular
ng new ace-app (Angular 13.3.2)
npm install ace-builds (ACE-Builds 1.4.14)
component.ts
import * as ace from 'ace-builds';
...
public aceEditor: ace.Ace.Editor;
#ViewChild('editor') private editor!: ElementRef<HTMLElement>;
...
ngAfterViewInit(): void {
// I don't understand why we don't set the "basePath" to our installed package
ace.config.set('basePath', 'https://unpkg.com/ace-builds#1.4.12/src-noconflict');
this.aceEditor = ace.edit(this.editor.nativeElement);
if (this.aceEditor) {
this.aceEditor.setOptions({
mode: 'ace/mode/sql',
theme: 'ace/theme/sqlserver',
});
}
component.html
<div #editor></div>
Result:
The editor is working, but now I need to somehow add a custom mode and theme.
Problems and Questions:
Is it correct to set the basePath to an external URL if I've the package already installed (obsolete due to Edit 1)?
How and where would I add the custom mode.js and theme.js?
How can I direct ace to the custom mode.js and theme.js?
Edit 1:
I managed to get rid of this line of code:
ace.config.set('basePath', 'https://unpkg.com/ace-builds#1.4.12/src-noconflict');
by directly importing the theme and mode with:
import 'ace-builds/src-noconflict/mode-sql';
import 'ace-builds/src-noconflict/theme-sqlserver';
the rest of the code did not have to be changed.
After looking through several projects and issues, I figured out that the best way to implement custom themes and modes for the ACE editor is to copy existing ones from ./node-modules/ace-builds/src-conflict and paste them to ./src/assets/ace.
Example:
Copy an existing mode (and optionally the theme) that represents your required syntax highlighting the most, in my case it was mode-sql.js. I copied the files to ./src/assets/ace and changed the import in my component.ts from:
import 'ace-builds/src-noconflict/mode-sql';
import 'ace-builds/src-noconflict/theme-sqlserver';
To:
import '../../../../assets/ace/mode-sql.js';
import '../../../../assets/ace/theme-sqlserver.js';
Everything else was kept exactly as described in the initial question. From there you can start to change the name of mode and theme, update the rules as well as the styling according to your requirements.

webpack creating 100's of js chunks crippling performance for a single page view with vue cli

We have a vuejs 2 project.
We needed some function of dayjs.
We abstracted the dayjs into a single utility file and following the guide ended up with this:
import { i18n } from '#/plugins/i18n';
import dayjs from 'dayjs';
import calendar from 'dayjs/plugin/calendar';
dayjs.extend(calendar);
export default async (date: Date, locale?: string): Promise<string> => {
import(`dayjs\locales\${locale}`)
const time:any = i18n.t('datetime.dict');
return dayjs(date).locale(userLocale).calendar(null, {
lastDay: `[${time.yesterday} ${time.at}] LT`,
sameDay: `[${time.today} ${time.at}] LT`,
nextDay: `[${time.tomorrow} ${time.at}] LT`,
lastWeek: `[${time.last}] dddd [${time.at}] LT`,
nextWeek: `dddd [${time.at}] LT`,
sameElse: 'LLLL'
});
};
The app works perfectly fine, but vuejs is outputting every single langauge file from dayjs as a chunk and also adding the prefetch script tag to the index.html.
Has anyone else hit this issue and is the above code snippet wrong or should there be a more precise import?
Here is a screenshot of only some of the dayjs chunks.. each is completely the same with different langauge strings in... but we didn't even import the locale setting options yet.
#MichalLevý gave the direction to the answer to this issue.
Essentially, webpack cannot know which single file to import when you say:
import(`dayjs\locales\${locale}`)
So.. it just creates a js chunk for every single file it finds. Which is not overly bad on its own.
When you combine this behaviour with vue-cli's default prefetch behaviour, this is when things get bad... the result is that every single chunk that webpack creates ends up being a "pre-fetched" line in the HTML head in the outputted index HTML file.
So when there is 400 chunks from a dynamic import (in this case locales from dayjs) then there is a prefetch for all of them.
It depends on your setup but.. for us, the app is also a PWA so there is effectively no requirement for prefetching as the PWA will also download... in fact it doubles the downloads.
The answer for us was to be more specific on the prefetch:
https://cli.vuejs.org/guide/html-and-static-assets.html#prefetch
And also, as we only needed a few languages, import only what was needed but being specific and not passing a variable to map to a path

How to import ErrorUtils in React Native

RN version: 0.50
Testing on Android, haven't tested on iOS
I am trying to use ErrorUtils.setGlobalHandler as described in this github issue: https://github.com/facebook/react-native/issues/1194
However, what is not clear from the issue is how to import ErrorUtils. It's not in the react documentation: https://facebook.github.io/react-native/docs/0.50/getting-started.html
Previously, in RN 0.41, I was able to import ErrorUtils with import ErrorUtils from "ErrorUtils"; However, in 0.50 I am getting a red react popup with the following message when I try to import ErrorUtils like this:
com.facebook.react.common.JavascriptException: Failed to execute 'importScripts' on 'WorkerGlobalScope': The script at 'http://localhost:8081/index.bundle?platform=android&dev=true&minify=false' failed to load.
I've also tried import { ErrorUtils } from 'react-native'; but it doesn't seem to exist there. The error is:
Cannot read property 'setGlobalHandler' of undefined
How do I properly import ErrorUtils in RN 0.50?
ErrorUtils is a global variable, therfore it doesn't need to be imported. You can verify this with console.log(global.ErrorUtils)
However it is exported as module anyways (here). The comment there also has more information why it is done this way.
You can import the module like this:
import ErrorUtils from 'ErrorUtils';
For anyone on RN61+, you should no longer import the module as you will experience the following error in the running metro bundler:
Error: Unable to resolve module `ErrorUtils`
Instead, just use the module without importing as this is a global variable, as stated by leo
I did created a global.d.ts to define a global variable,
interface Global {
ErrorUtils: {
setGlobalHandler: any
reportFatalError: any
getGlobalHandler: any
}
}
declare var global: Global
then, at where you are trying to use it, simply
global.ErrorUtils.setGlobalHandler(xxxx)