I want to setup a command on my package.json that can do the TS files linting on my react App (using CRA that provides the app with react-scripts 3.1.2).
I saw that tslint is getting deprecated and that's why the react community is moving to ESlint.
There are some clues on the package.json file, like:
"eslintConfig": {
"extends": "react-app"
}
So my idea is that when I run the eslint, it can take that configuration and use all the CRA setup.
I tried :
"lint" : "eslint --ext=jsx,ts,tsx src"
But no luck, since I put some errors on the code and it still do not show me any information.
Any clues?
So I found a good approach. My idea was to keep everything working with the CRA standards and reuse everything (not sure why nobody adds this on the CRA, probably I will add a PR on the future to check)
This fixed the thing, reusing all the dependencies that CRA uses:
On package.json (standard for CRA)
"eslintConfig": {
"extends": [
"react-app",
"plugin:react/recommended",
"plugin:#typescript-eslint/recommended"
]
}
And then you can add a lint script:
"lint" : "eslint ./src/**/*.{tsx,ts}",
I hope that this will help someone :-)
Also, if someone knows more about the good practice on this, it will be very appreciated!
PD: .eslintignore is also working fine
Related
I inherited a react project that was working on my last computer. But now it can't build on my new computer. Specifically, I forgot how to get the npm start command to know where the project directory is.
For example, let's say I have the following two files:
// src/template/Page.js
import LoginComponent from 'component/Login.js'
// src/component/Login.js
export default function Gallery() { return <div></div>;}
Then when I run npm start, I get the error:
Module not found: Can't resolve 'component/Login.js' in 'src/template/Page.js'
I vaguely remember that on my last computer, I used some hidden file, or possibly the .env file to tell npm to look for all react components under the src/ directory, such that the term src/ can be omitted from all the import statements in the code.
Does anyone know how to tell react or npm to always import components without always spelling out the src/ prefix?
NOTE:
I also see a .vscode directory with these files:
// .vscode/settings.json
{
"editor.snippetSuggestions": "top",
"files.associations": {
"*.js": "javascriptreact"
},
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": false
},
"compilerOptions": {
"baseUrl": "src"
}
}
// .vscode/launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": "Chrome",
"type": "chrome",
"request": "launch",
"url": "http://localhost:3000",
"webRoot": "${workspaceRoot}/src"
}
]
}
I think these files might be related to my solution last time I got this working
In my package.json, I see these lines:
...
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
}
...
Also, my package.json says I'm using "react": "^16.6.1" and my npm -v shows 5.5.1. I don't remember what npm version I was using on my last computer. So not sure if that would matter.
You need a jsconfig.json to configure absolute imports (if you were using TypeScript, you would instead use tsconfig.json). This file is vital to your project working correctly, so you should commit this to source control so you don't have to remake it on each machine:
{
"compilerOptions": {
"baseUrl": "src"
},
"include": ["src"]
}
I did not know Create React App supported this, I learned something today from your question. Thanks!
Finally got it work. I added this line to my .env file:
NODE_PATH=src
And then everything worked. Taken from documentation here: https://nodejs.org/api/modules.html
If the NODE_PATH environment variable is set to a colon-delimited list
of absolute paths, then Node.js will search those paths for modules if
they are not found elsewhere.
On Windows, NODE_PATH is delimited by semicolons (;) instead of
colons.
NODE_PATH was originally created to support loading modules from
varying paths before the current module resolution algorithm was
defined.
NODE_PATH is still supported, but is less necessary now that the
Node.js ecosystem has settled on a convention for locating dependent
modules. Sometimes deployments that rely on NODE_PATH show surprising
behavior when people are unaware that NODE_PATH must be set. Sometimes
a module's dependencies change, causing a different version (or even a
different module) to be loaded as the NODE_PATH is searched.
Additionally, Node.js will search in the following list of
GLOBAL_FOLDERS:
1: $HOME/.node_modules
2: $HOME/.node_libraries
3: $PREFIX/lib/node
Where $HOME is the user's home directory, and $PREFIX is the Node.js
configured node_prefix.
These are mostly for historic reasons.
It is strongly encouraged to place dependencies in the local
node_modules folder. These will be loaded faster, and more reliably.
I have a Chrome Extension built with Parcel and React, but I'm not getting warnings (e.g. missing useEffect dependencies) when I inspect the popup. How do I get these warnings?
Missing useEffect dependencies warnings are provided by eslint through this plugin. Parcel won't run eslint for you unless you set it up through the #parcel/validator-eslint plugin. I provided instructions on how to do that in this answer.
Another option is to use eslint-watch (npm) from the command line separately from parcel, so you'd have two separate scripts in your package.json that might look like this:
{
"scripts": {
"start": "parcel src/index.html"
"lint": "esw --watch src/**/*.js"
}
}
To get react hooks warnings, you'll need to use eslint-plugin-react-hooks by first installing it (e.g. yarn add eslint-plugin-react-hooks --dev), and then adding this to your .eslintrc.json:
{
"extends": [
// ...
"plugin:react-hooks/recommended"
]
}
Background and introduction
As a developer in React.js I highly appreciate the automated help I
can get from ESLint on code issues such as
unused identifiers.
I have a very small example project in a zip file
that I use for experimenting with ESLint.
1
Even without explicit ESLint rules, Visual Studio Code indicates what
identifiers are unused by showing them in a less vibrant color.
In the screenshot below, unUsedArgument and unUsedVariable would
have been displayed in about the same color as prevToggle, had they
been used.
App.js written out :
// App.js
import React, { useCallback, useState } from 'react';
import './App.css';
import Button from './components/UI/Button/Button';
function App(unUsedArgument) {
const [unUsedVariable, setShowParagraph] = useState(true);
const showParagraphFcn = useCallback(() => {
setShowParagraph((prevToggle) => !prevToggle);
},[]);
console.log('App RUNNING');
return (
<div className='app'>
<h1>Hi there!</h1>
<Button onClick={showParagraphFcn}>A Button</Button>
</div>
);
}
export default App;
After downloading the mentioned zip file, running npm install
and then npm start, a web page opens in my default web browser.
Pressing F12 makes it look as below.
2
The screenshot shows that – without ESLint – no errors or warnings are
displayed in the console of the browser.
This is despite the fact that both unUsedArgument and
unUsedVariable are indeed unused.
package.json – from start :
{
"name": "Disable warnings when prefixed with underscore (_)",
"dependencies": {
"#testing-library/jest-dom": "^4.2.4",
"#testing-library/react": "^9.4.1",
"#testing-library/user-event": "^7.2.1",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-scripts": "4.0.3"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"browserslist": {
"development": [
"last 1 chrome version"
]
}
}
In addition, I have an eslintConfig.json file whose contents were
originally in package.json, but which I deliberately removed from
there to see how the behavior would be affected.
eslintConfig.json :
,
"eslintConfig": {
"extends": "react-app"
}
When running npm install, the ESLint packages are downloaded – 18
subdirectories of node_modules containing the word eslint.
(This happens because the package react-scripts depends indirectly
on the ESLint packages.)
Here is how to run the ESLint command from the command line.
npx eslint . --ext .js
The first three lines of the response indicate that ESLint was
installed, but not configured :
Oops! Something went wrong! :(
ESLint: 7.32.0
ESLint couldn't find the plugin "eslint-plugin-react".
My next action is therefore to add the eslintConfig attribute
(back) into package.json.
3
After doing so, the result of running npx eslint . --ext .js is :
The warning reads :
'unUsedVariable' is assigned a value but never used no-unused-vars
Thus, without any further configurations, ESLint warns about the
unused variable but not about the unused argument (parameter).
I would prefer to be warned about both identifiers that are unused.
In addition, I would like to have the option to disable ESLint
warnings for unused arguments and variables that start with an
underscore (_).
Having such a rule would mean that I could easily turn off these
warnings – permanently or temporarily – by simply prefixing the
identifier with _ (an underscore).
In Visual Studio Code I can achieve this by adding a specially
designed ESLint comment.
4
/*eslint no-unused-vars: ["warn",{"argsIgnorePattern": "^_","varsIgnorePattern": "^_"}]*/
The question I want to ask
This is all looking good.
But what I don't like, is to clutter my JavaScript code with ESLint
comments in all files.
I would prefer to set the ESLint rules for the whole project so that
all JavaScript files automatically adhere to these rules.
How can I get this exact behavior without scattering ugly ESLint
comments all over my JavaScript code?
References
ESLint
Zip file containing the needed project files
Create React App (CRA)
The package react-scripts depends indirectly on ESLint packages
To install ESLint globally rather than locally
(npm install eslint --global) is not recommended
VS Code ESLint extension
In VS Code, add "eslint.nodePath": "C:\\Program Files\\nodejs",
to settings.json
1
The project was originally created as a Create React App (CRA).
I have since deliberately removed the
eslintConfig attribute in package.json for experimental purposes.
2
For me, the npm install command has taken any time from 4 to 11
minutes to complete.
The npm install command downloads and installs all Node.js packages
listed in the package.json file.
The npm start command starts a local web server and opens the
public/index.html file in your default web browser, in my case
Google Chrome Version 98.0.4758.102, 64-bit, running on Windows 10.
When you want to close the server, do so it by hitting
Ctrl+C.
3
No need to run npm install this time, as no packages are affected.
4
This is likely true for many other text editors and IDE:s as well,
such as for example WebStorm by JetBrains.
How can I get this exact behavior without scattering ugly ESLint
comments all over my JavaScript code?
Just add rules under the eslintConfig attribute, to make
package.json look as follows.
1
package.json :
{
"name": "Disable warnings when prefixed with underscore (_)",
"dependencies": {
"#testing-library/jest-dom": "^4.2.4",
"#testing-library/react": "^9.4.1",
"#testing-library/user-event": "^7.2.1",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-scripts": "4.0.3"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"browserslist": {
"development": [
"last 1 chrome version"
]
},
"eslintConfig": {
"extends": "react-app",
"rules": {
"no-unused-vars": [
"warn",
{
"argsIgnorePattern": "^_",
"varsIgnorePattern": "^_"
}
]
}
}
}
Now you can remove the ESLint comment from App.js and still get the
desired behavior.
Check to see that you were successful:
npx eslint . --ext .js
Expect to see:
If your text editor (VS Code in my case) is still open, make sure that
you restart it before you expect to see this new behavior.
Play around in your text editor by adding and removing an underscore
prefix to see the warning go away and appear again.
Note!
I advise against putting the ESLint rules in a separate
.eslintrc.* configuration file.
2
References
Looong answer to Parsing error: The keyword 'import' is reserved
Short answer to Parsing error: The keyword 'import' is reserved
#babel/eslint-parser – usage
How to disable warnings about unused identifiers (TypeScript)
1
In this case there's no need to run npm install.
Just adding the rules attribute under eslintConfig is enough.
2
If you want to know why, compare this long answer with this short answer.
Create-react-app allows you to extend the ESLint config that comes with create-react-app:
https://create-react-app.dev/docs/setting-up-your-editor#experimental-extending-the-eslint-config
However when I try to do this in my own project i just get this error
(Image of error)
Error
Error: Cannot find module 'eslint-config-shared-config'
Command run
eslint --ignore-path .gitignore --ext .js,.ts,.tsx .
.eslintrc
{
"extends": ["react-app", "shared-config"],
"rules": {
"additional-rule": "warn"
},
"overrides": [
{
"files": ["**/*.ts?(x)"],
"rules": {
"additional-typescript-only-rule": "warn"
}
}
]
}
A safe way to setup a base ESLint config file to build upon is by following the ESLint usage guide
$ npx eslint --init
# or
$ yarn run eslint --init
Like #jonrsharpe said, shared-config is just an example that cannot be used literally, the docs was trying to explain that you could use shared configurations.
For example, if you add an ESLint plugin with a shared-config rule set, then you could use that as indicated by the example.
Difference between plugins and extends in ESLint
EXTEND_ESLINT flag was removed in react-scripts v4
I've found a ton of "solutions" for this, ranging from simple package.json additions to custom hack modules, but none worked for me.
I simply want to override the eslint settings for an out-of-the-box, NON ejected create-react-app.
Namely, the rule "no-unused-vars".
I'm using Visual Studio Code.
I seem to have fixed this accidentally just trying combinations of things I found online. This seems to have worked.
1) I created a .env file in the project root (where the package.json file is). In it I have:
// .env file
EXTEND_ESLINT = true
2) Then I created a .eslintrc file (no extension) in my project root and added this:
// .eslintrc file (no extension)
{
"extends": [
"react-app"
],
"rules": {
"no-unused-vars": "off"
}
}
The library now supports extending the pre-defined ESLint rules natively, see the relevant docs.
The gist of it is that you will have to set the EXTEND_ESLINT environment variable, and then add your own ESLint config to the project root, optionally extending create-react-app's:
{
"eslintConfig": {
"extends": ["react-app"],
"overrides": [
{
"files": ["**/*.js"],
"rules": {
"no-unused-vars": "warn"
}
}
]
}
}
In the create-react-app project package.json is ready, you just need to add the rules field.
package.json
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
],
+ "rules": {
+ "react/self-closing-comp": 1
+ }
},
It's important to note that any rules that are set to "error" will stop the project from building.
create-react-app uses eslint-config-react-app, which contains almost all popular eslint packages.
eslint-plugin-flowtype
eslint-plugin-import
eslint-plugin-jest
eslint-plugin-jsx-a11y
eslint-plugin-react
eslint-plugin-react-hooks
eslint-plugin-testing-library
eslint-config-react-app github
https://github.com/facebook/create-react-app/tree/main/packages/eslint-config-react-app
eslint-config-react-app npm
https://www.npmjs.com/package/eslint-config-react-app
its not hard, just follow these steps:
npm i -D eslint eslint-plugin-react
npx eslint --init
edit the generated config file, for example .eslintrc.json
put your rules in the "rules": { ... } section