'React' was used before it was defined - reactjs

I am working with create-react-app + typescript + eslint application and during build have such error:
Line 1:8: 'React' was used before it was defined #typescript-eslint/no-use-before-define
Code in my component starts with:
import React from "react";
Eslint settings:
module.exports = {
parser: "#typescript-eslint/parser",
parserOptions: {
ecmaVersion: 2020,
sourceType: "module",
ecmaFeatures: {
jsx: true
}
},
settings: {
react: {
version: "detect"
}
},
extends: [
"plugin:react/recommended",
"plugin:#typescript-eslint/recommended",
"prettier/#typescript-eslint",
"plugin:prettier/recommended"
],
rules: {
"#typescript-eslint/explicit-module-boundary-types": 0,
"#typescript-eslint/triple-slash-reference": 0,
"no-use-before-define": "off",
"#typescript-eslint/no-use-before-define": "off"
},
};
Some part of package.json:
"devDependencies": {
"#typescript-eslint/eslint-plugin": "^4.1.0",
"#typescript-eslint/parser": "^4.1.0",
"babel-eslint": "^10.1.0",
"eslint": "^6.6.0",
"eslint-config-airbnb": "^18.1.0",
"eslint-config-prettier": "^6.11.0",
"eslint-plugin-import": "^2.20.2",
"eslint-plugin-prettier": "^3.1.3",
"eslint-plugin-react": "^7.20.0",
"prettier": "^2.0.5",
"start-server-and-test": "^1.11.3"
},
"dependencies": {
...
"react-scripts": "3.4.3",
...
}
I tried:
Read https://github.com/typescript-eslint/typescript-eslint/issues/2502
Disable #typescript-eslint/no-use-before-define and no-use-before-define in .eslintrc.js
Actually I tried to delete .eslintrc.js at all, but had the same error.

From the official documentation.
"rules": {
// note you must disable the base rule as it can report incorrect errors
"no-use-before-define": "off",
"#typescript-eslint/no-use-before-define": ["error"]
}

The bug occurs due to mismatch of #typescript-eslint versions in react-scripts and your local package.json - GitHub issue
You can downgrade the packages until react-scripts updates their version.
"#typescript-eslint/eslint-plugin": "4.0.1",
"#typescript-eslint/parser": "4.0.1",
EDIT 2020-09-14
It seems the bug is not related to react-scripts version of #typescript-eslint since multiple people reported the same bug without using react-scripts.
Anyway, the workaround remains the same - downgrade to the working version of #typescript-eslint until the fix is available.
EDIT 2020-10-24
react-scripts#4.0.0 has been published with updated #typescript-eslint. Using the newest version should solve the issue.
EDIT 2020-11-04
If after upgrading the packages the error is still there, most probably your eslint config uses the wrong rule. Check out Igor's answer to fix it.

If you are only getting this error for .js files, make sure #typescript-eslint/parser is being used exclusively on Typescript files.
.eslintrc.json (abbreviated)
{
"overrides": [
{
"files": ["**/*.ts", "**/*.tsx"],
"plugins": ["#typescript-eslint"],
"rules": {
"no-use-before-define": "off",
"#typescript-eslint/no-use-before-define": ["error"],
},
}
],
// WRONG: Do not use #typescript-eslint/parser on JS files
// "parser": "#typescript-eslint/parser",
"plugins": [
"react",
// "#typescript-eslint"
],
}

That is how I resolved my problem.
First of all, go to the node_modules/react-scripts/config/webpack.config.js and change cache to false, because this will help you to understand what works and what is not then you changing eslint file. I found it here
cache: true, // You can set it to false
formatter: require.resolve('react-dev-utils/eslintFormatter'),
Add ENV varialbe to .env file. More info
EXTEND_ESLINT=true
From now CRA will have to use your local eslint for linting during your build and we have control to disable some rules, in my case in .eslintrc:
rules: {
"#typescript-eslint/no-use-before-define": "off"
},

I landed on this page after I started getting issues with a Gatsby project that was using Typescript and an ESLint config that extended eslint-config-airbnb-typescript. In addition to OP's error, ESLint was also giving errors on various rules not being defined, like Definition for rule '#typescript-eslint/no-redeclare' was not found. and a few others.
The underlying problem ended up being that Gatsby was using fairly old versions of both #typescript-eslint/eslint-plugin and #typescript-eslint/parser. Forcing yarn to install only up-to-date versions solved the issue:
// package.json
"resolutions": {
"#typescript-eslint/eslint-plugin": "^4.4.0",
"#typescript-eslint/parser": "^4.4.0"
}

My fix for that:
Use eslint 6 as react-scripts is using
Force react scripts to use newer #typescript-eslint packages as the rest of the repo.
I'm using selective resolution here
"resolutions": {
"**/react-scripts/**/#typescript-eslint/eslint-plugin": "^4.4.1",
"**/react-scripts/**/#typescript-eslint/parser": "^4.4.1"
}
#typescript-eslint 4.x does still support es6

I got this error from the airbnb-base ruleset in a typescript project. Also extending airbnb-typescript (that has the correct rules for typescript) resolved the issue.

This has been resolved in 4.4.0. Upgrade these dependencies to version 4.4.0
Update: This may work for some use cases. This resolved my issue.
"#typescript-eslint/eslint-plugin": "^4.4.0",
"#typescript-eslint/parser": "^4.4.0",

I just wanted to add that for me, I did the following.
Removed all eslint related dependencies from package.json if they were already included in package-lock.json by react-scripts (for me that was all of them)
Deleted my node_modules folder, and package-lock.json file
Ran npm install
After completing those steps I finally got that error to go away. I prefer removing the dependencies to downgrading them since this will help avoid the same issue happening again in the future.

Try adding import/resolver to your Eslint settings:
"settings": {
"react": { "version": "detect" },
"import/resolver": { "typescript": {} }
}
Maybe you will need to install it too:
$ yarn add -D eslint-import-resolver-typescript
If that doesn't work, you could change this rule
"#typescript-eslint/no-use-before-define": "off"
like this:
"no-use-before-define": "off"

It is an issue present in ESLINT.
The way I resolve is to add the following lines to the ESLINT/rules:
"no-use-before-define": [0],
"# typescript-eslint / no-use-before-define": [1],

If you use Create React App. Getting the latest version of react-scripts fixed this issue for me. Currently: 4.0.3
// Get this specific version:
npm uninstall react-scripts
npm install react-scripts#4.0.3
// Get latest version:
npm uninstall react-scripts
npm install react-scripts

(not enough rep to comment)
#sashko's workaround seems to work - deleting node_modules was necessary as well.
One thing I missed was the caret in "^4.0.1". The version needs to be fixed without the caret ^, which seems to be the issue that #Rolly is having. Make sure it's 4.0.1.
Only a workaround until react-scripts updates to v4 (I'm using create-react-app)

deleting the node_modules folder and reinstalling it worked for me. I'm using yarn as package manager.

I deleted packages #typescript-eslint/eslint-plugin and #typescript-eslint/parser from my package.json,
deleted node_modules and package-lock.json,
reinstalled packages: npm install
The error disappeared.
UPDATE
After that create-react-app uses their own #typescript-eslint/eslint-plugin module which is deprecated.

This Answer worked for me in a react-native project(airbnb style guide)
Extend your rules with airbnb-typescript inside the .eslintrc.json
"extends": {
"airbnb-typescript"
}
Press ctrl+shift+p or cmd+shift+p >Reload window (or simply close and re-open vscode)

Try using Yarn instead of NPM (make sure to remove your node_modules in between).
This worked for me.

Related

"No files matching the pattern "src" were found." when using "npx eslint src" or "npx eslint src/"

I've just set up a create-react-app project with typescript. I've added eslint with npx eslint --init. When I run npx eslint src/ or npx eslint src I get an error:
Oops! Something went wrong! :(
ESLint: 8.18.0
No files matching the pattern "src" were found.
Please check for typing mistakes in the pattern.
However, if I use this command: npx eslint src/* then it works. This is fine, but some guides and stackoverflow comments (eg on here) I've seen show that the commands that don't work for me are working for seemingly everyone else. What am I doing wrong?
eslint.js
module.exports = {
env: {
browser: true,
es2021: true,
jest: true,
},
extends: ["plugin:react/recommended", "standard"],
parser: "#typescript-eslint/parser",
parserOptions: {
ecmaFeatures: {
jsx: true,
},
ecmaVersion: "latest",
sourceType: "module",
},
plugins: ["react", "#typescript-eslint"],
rules: {
semi: "off",
quotes: "off",
"space-before-function-paren": "off",
},
ignorePatterns: ["**/*.css", "**/*.svg"],
};
package.json:
"dependencies": {
"#testing-library/jest-dom": "^5.14.1",
"#testing-library/react": "^13.0.0",
"#testing-library/user-event": "^13.2.1",
"#types/jest": "^27.0.1",
"#types/node": "^16.7.13",
"#types/react": "^18.0.0",
"#types/react-dom": "^18.0.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"typescript": "^4.4.2",
"web-vitals": "^2.1.0"
},
"devDependencies": {
"#typescript-eslint/eslint-plugin": "^5.30.0",
"#typescript-eslint/parser": "^5.30.0",
"eslint": "^8.0.1",
"eslint-config-standard": "^17.0.0",
"eslint-plugin-import": "^2.25.2",
"eslint-plugin-n": "^15.0.0",
"eslint-plugin-promise": "^6.0.0",
"eslint-plugin-react": "^7.30.1"
},
Okay the comments I left were incorrect. This question left me reading about ESLint, how it works, and how the npm/npx commands differ.
So here is the deal
NOTE: "I use the syntax $(pwd) to refer to the current-working-directory, because it's not a pseudo representation of a path, but rather a command, wrapped as such, that it can be interpreted, and ran, by the BASH shell."
In the comments, I wrote about eslint resolving paths, and its inability to infer the meaning of the CLI passed argument src, as shown in this snippet:
/* COMMAND-1 */
$ eslint src
Thinking back on it, that was a really dumb comment to make, that I shouldn't have said. The reason it wasn't smart, is because, the way the path is resolved completely changes when you use the following:
/* COMMAND-2 */
$ npx eslint src
Looking at the two commands together, side by side, is helpful in the sense that it allows us to draw a side by side comparison, however, there really isn't much to compare, because of how different these two commands are.
So the first command, COMMAND-1, resolves src as if it were a path, however, COMMAND-2 executes an ESLint internal command, hence the "X" in npx, which is the same as executing...
npm exec or npm x
In other words, the following; npx eslint src can also be executed using npm x eslint src, or npm exec eslint src.
So, as stated above, **the argument src is not a system file-path, but rather, it's an internal ESLint command that offers a cute little CLI printout of your errors. ITS ACTUALLY PRETTY COOL
Initially the Command didn't work for me either
The problem I had, looks, like it was the same problem your having.
The solution is quite simple.
Update NPM to the latest version.
Update NPX to the latest version. (more on this below)
Update Node.js to the latest version
Update ESLint to the latest version
Update all of your proj's pkgs, then audit them with the fix command (more on this below).
So NPM comes with the NPX command embedded in it, and technically, npx is the npm command, just ran as npm x or npm exec, however; from the standpoint of your file-system, (in other words, looking at the commands from the context of /usr/bin/...) they are two different commands.
So I know alot about ubuntu because it was my OS for 7 years. About a year ago I switched to Fedora 36: Workstation and was glad I did. I made the change because of the issues associated with installing Node.js & NPM. Ubuntu makes it difficult. The reason I use Linux in the first place is because software runs in an environment that suited for running software, and not suited for protecting the proprietary licenses associated with the software. Anyways, long story made short... the best way for you to upgrade NPX (which means upgrading NPM, which means you need to upgrade Node.js), is to install the latest version of Node.js, go into the directory, and create symbolic links for npm, node, npx, in your /usr/bin directory and then upgrade eslint (globally) to version v8.18.0. You may also need to create a symbolic link for ESLint.
On a final note, just to point out somthing. You notice your ESLint version your package.json file is v8.18.0? and the version in the error you are getting is v8.1.0?
That is because your local & global eslint installs are different versions of eslint. You should try to always keep everything the same version.
Right now your system is trying to execute npx eslint src as if src is a path, but one everything is updated, you should have the software needed, for eslint & npm to know that its an ESLint command your trying to execute, not a path.
I think you should have this property in tsconfig.ts file :
"baseUrl": "."

babel/polyfill is deprecated warning in create-react-app

I have a React app that I created using npx create-react-app my-app. I've been regularly updating both React and other npm packages.
A while ago, I started getting the following warning:
#babel/polyfill is deprecated. Please, use required parts of core-js
and regenerator-runtime/runtime separately
The following is what's in my package.json file:
"devDependencies": {
"babel-polyfill": "^6.26.0",
"redux-devtools": "^3.5.0"
}
I found a few articles online about how to handle this but none of them look like the official solution. What's the right way to handle this?
So far, this has been a warning and not an error so I just postponed dealing with it. Today, I upgraded the moment package and that started giving me an error and I figured dealing with this issue first is a good starting point.
I'd appreciate some pointers in making this warning go away.
babel-polyfill is being replaced by core-js. You can remove babel-polyfill and install core-js instead. After you have installed core-js update the babel presets in your .babelrc or babel.config.js file with the following:
"presets":[
['#babel/preset-env',
{
useBuiltIns: 'usage',
corejs: 3,
}],
]
If you are importing babel-polyfill in your App you can remove that too. Also you can add a targets property in your presets
[
'#babel/preset-env',
{
targets: {
browsers: ['> 0.25%, not dead'],
},
useBuiltIns: 'usage',
corejs: 3,
},
]

Cannot find module 'babel-preset-react'

This is my first React Native project. The repo is here.
When I start up expo, I get the error:
Cannot find module 'babel-preset-react'
Among others, it has these dependencies:
"expo": "^32.0.0",
"react": "16.8.4",
"react-native": "https://github.com/expo/react-native/archive/sdk-32.0.1.tar.gz",
"#babel/core": "7.3.4",
"babel-core": "^7.0.0-bridge.0",
"#babel/preset-react": "^7.0.0",
I found these four libraries in my app's /node_modules that each contain a dev dependency on "babel-preset-react":
hoist-non-react-statics, prop-types, react-input-autosize and
react-proxy.
None of these have newer versions that depend on "#babel/preset-react".
I had this a few, every time I install a new module/plugin.
My solution has been to delete node_modules folder and yarn install or npm install.
It stops the error. I'm not sure is the right solution (would be interested to know if it is), but works.
I had to change ['react'] to ['#babel/preset-react'] in .bablerc when upgrading from babel 6.x to 7.x:
{
"presets": [
"#babel/preset-env",
"#babel/preset-react",
]
}
This seems to be an issue to do with an expo project being in a bad state.
Expo is an express set of libs with the goal of simplifying development, but it is not compatible with most react native examples in the wild.
After further review, it looks like you may have followed a regular react native example in an Expo based project, without first ejecting.
I had a similar issue wherein I mistyped babel/preset-react as babel-preset-react in the babel config file.
Correcting the typo helped me resolve the issue.
I had this issue after an upgrade. I needed a restart and it was solved. Apparently some caching issue or running process which still uses an old dependency.
First of all make sure the babel config has '#babel/preset-react' in presets and not 'babel-preset-react'
Apart from that. this did it for me:
npm i #babel/preset-react
npm i #babel/core

Storybook breaks MobX/MobX-React?

I've confirmed it 100% although I cannot diff the node_modules to determine how. But here's the issue.
Versions:
"react": "^16.6.3",
"react-dom": "^16.6.3",
"mobx": "^5.6.0",
"mobx-react": "^5.4.2"
"devDependencies": {
"#storybook/addon-actions": "^4.0.9",
"#storybook/addon-knobs": "^4.0.9",
"#storybook/addon-links": "^4.0.9",
"#storybook/addon-notes": "^4.0.8",
"#storybook/react": "^4.0.9"
}
When I run npm run start before installing storybook, my application runs which has a hefty amount of necessary #observable usage. None of the observables are undefined at this point, which is great and expected.
After I run npm i --save-dev #storybook/react #storybook/addon-notes #storybook/addon-links #storybook/addon-actions #storybook/addon-knobs
and then run npm run start again, I get a full on Failure to compile error. In my AppStore.js (which I cannot disclose) as the source of undefined variables I use the #observable decorator in. The failure message shows all of those and declared #observable in two other components using #observable as undefined.
I don't understand how adding storybook would break MobX or MobX-react at runtime. If anything, I would think that it would be npm run storybook that would cause errors. I thought maybe it's because of webpack.config.js in .storybook directory, but I can't be sure.
Also, for anyone who would think the problem is babel plugins, it is not. I am correctly using this in the correct order:
"babel": {
"plugins": [
"transform-decorators-legacy"
],
"presets": [
"react-app"
]
},
Lastly, when I run npm uninstall --save-dev #storybook/react #storybook/addon-notes #storybook/addon-links #storybook/addon-actions #storybook/addon-knobs
running npm run start works fine!
I'll try to answer my own question here. It's difficult to determine what in node_modules from storybook is affecting runtime for Mobx in webpack config.
Please help or make any suggestion!

React-Native: Failed to load bundle. Cannot read property 'throwlfClosureRequired'

The app installs and opens but right when it opens this red screen appears with the below error message.
TBH I am not quite sure what I am doing and I really need some help. I was able to get my other project to work but when I started my second project this came up when trying to run the code. The code is just the basic code you get when you run: react-native init projectName
Change the version of "babel-preset-react-native" to "4.0.0". For the lastest version 5.0.0, the issue arises.
Run npm install after the version change. Then start the emulator.
Even then if you face issue, delete your node_modules directory, repeat step 1.
Restart your machine if you see the issue again even after all tries.
Check github issue
I got the above mentioned error just now. I am using React Native v0.57 and my json file had this
{
"name": "AwesomeProject",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start",
"test": "jest"
},
"dependencies": {
"react": "16.5.0",
"react-native": "0.57.1"
},
"devDependencies": {
"babel-jest": "23.6.0",
"jest": "23.6.0",
"metro-react-native-babel-preset": "0.45.6",
"react-test-renderer": "16.5.0"
},
"jest": {
"preset": "react-native"
}
}
I added "babel-preset-react-native": "4.0.0", and removed "metro-react-native-babel-preset": "0.45.6" in the "devDependencies" and the error was resolved.
Jonathan's solution worked for me as well:
Fixed. babel pushed an update that pushed to 5.0.0. set your presets to 4.0.0 and it will fix it.
https://github.com/facebook/react-native/issues/18962
I have upgraded to
"react-native": 0.57.7
"metro-react-native-babel-preset": "0.48.5",
Now the bundle is loading as expected.
My current version:
"react-native": "0.57.8",
"metro-react-native-babel-preset": "0.51.1",
Here how I fixed:
add
"devDependencies": {
"babel-preset-react-native": "4.0.0"
},
remove node_modules
npm install
VoilĂ ! It works!
Fixed. babel pushed an update that pushed to 5.0.0. set your presets to 4.0.0 and it will fix it.
https://github.com/facebook/react-native/issues/18962
^^ what they said... change your "babel-preset-react-native" to 4.0.0 .
Try this command
react-native upgrade
Had the same issue. Downgrading to "babel-preset-react-native": "4.0.0", did not work.
running this worked for me
npm add #babel/runtime
Try the followings:
clean the build folder and try again.
run react-native start --reset-cache in one tab
and then
run react-native in another tab
For me this answer worked:
https://stackoverflow.com/a/40966360/4483716
Basically I needed to give permission to folder
/Users/[username]/Library/LaunchAgents.
Use this command:
$ sudo chown $(whoami) /Users/$(whoami)/Library/LaunchAgents
Add babel-preset-react-native version 4.0.0 to your devDependencies in package.json
"devDependencies": {
"babel-preset-react-native": "4.0.0"
},
npm install
react-native run-ios or android
If it still doesn't work try rm -rf node_modules/ and redo step 2 & 3

Resources