ESLint in VSCode not fixing on save - eslint

I am using ESLint in my Vue(Nuxt) project in VSCode. When I save I would like my ESLint to run automatically and fix all the warnings for me automatically.
This is my settings.json file in VSCode:
{
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"vetur.format.defaultFormatter.js": "vscode-typescript",
"vetur.validation.template": false,
"vetur.completion.scaffoldSnippetSources": {},
"vetur.completion.useScaffoldSnippets": false,
"vetur.format.defaultFormatter.html": "none",
"workbench.iconTheme": "material-icon-theme",
"git.autofetch": true,
"git.defaultCloneDirectory": "",
"gitlens.views.repositories.files.layout": "list",
"editor.tabSize": 2,
"editor.detectIndentation": false,
}
And this is my .eslintrc.js file:
module.exports = {
root: true,
env: {
browser: true,
node: true,
},
extends: [
"#nuxtjs",
"plugin:nuxt/recommended",
"../.eslintrc.js"
],
rules: {
//Add custom rules for the frontend here.
//Rules that are common for shared, frontend and backend should go in the parent file
"nuxt/no-cjs-in-config": "off",
},
}
The linked ../.eslintrc.js file contains the following:
module.exports = {
parserOptions: {
parser: 'babel-eslint',
},
plugins: ['jest'],
rules: {
'prefer-const': 'off',
'comma-dangle': ['error', 'always-multiline'],
'prefer-template': 'error',
},
env: {
'jest/globals': true
}
}
Whenever I save the file the warnings just show up and will not automatically fix themselves.
EDIT:
I've turned on verbose output and i'm seeing this in the output:
(node:6832) UnhandledPromiseRejectionWarning: Error: Failed to load plugin 'import' declared in 'frontend\.eslintrc.js » #nuxtjs/eslint-config': Cannot find module 'eslint-plugin-import'
Require stack:
I've then ran yarn add eslint-plugin-import and tried again, it still returns the same error.

Get eslint plugin, add this code to your settings.json
{
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"eslint.validate": ["javascript"]
}
source

Launch VSCode,
Command + Shift + P, type settings and hit enter, paste and save the following:
{
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true,
}
}
You're good to go!

I've managed to fix the issue.
The problem was that there were multiple working directories in my solution, which all have their own eslint config.
Putting the following line in the settings.json file of VSCode solved my issue:
"eslint.workingDirectories": [{ "mode": "auto" }]

I tried those solutions and others, and it still didn't work. Actually it was just that ESLint's use had to be approved for use in VSCode. That is, I clicked on the ESLint item on the editor's bottom bar:
Which opened a popup asking me to approve ESLint. After approval autocorrect was running as expected.

Install ESLint extension from the VSCode marketplace.
Once the ESLint extension has installed you may use CTRL + SHIFT + P to open the Command Palette. Search “ESLint fix all auto-fixable Problems” and press enter.
This command would enable eslint to fix the file on save.

In the snap above as you can see that I am getting eslint errors and just to inform you all that despite saving the file, all auto-fixable problems are were not getting fixed by eslint/prettier setup.
So I tried pressing ctrl+shift+p and selecting prettier as default formatter and also tried doing eslint restart server but that didn't worked.
I noticed that vscode was giving me some notifications at the bottom right corner (bell icon). I clicked on that and some list of pop up came up stating that there are multiple formatters installed for the same extension file. Like for example in the below snap there is .jsx file(it had two formatters one was prettier and other was vscodes inbuilt formatter). I clicked on configure button and selected prettier as default and when I saved the file it worked!
If this doesn't works for you then I think this all worked for me because I had eslint npm packages installed in my project that works with prettier to enforce the prettier rules. (these packages are eslint-config-prettier and eslint-plugin-prettier)

I ran into a similar problem-- ESLint was not properly formatting only certain, seemingly random, files on save. Running ESLint --fix would fix the formatting errors, but saving would not. Adding this line to our workspace settings.json fixed the problem:
"eslint.format.enable": true,
Making all our formatter settings look like this:
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll": true
},
"eslint.format.enable": true,
You can also go into the ESLint extension settings and check off the checkbox labeled ESLint > Format:Enable. Worked like a charm!

What fixed it for me was adding this to settings.json, because VSCode didn't know what formatter I wanted to be used on save:
"[javascript]": {
"editor.defaultFormatter": "dbaeumer.vscode-eslint"
},

Check if in the settings.json there are other formatters enabled, in my case I had this by mistake.
"[javascript]": {
"editor.defaultFormatter": "vscode.typescript-language-features"}

After getting the Eslint plugin you need to add this line to the settings.json:
{
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
}
Still not working? check if your eslint works fine by running this in the terminal:
eslint --ext \".js,.vue\" --ignore-path .gitignore .
If it failed with exit code 2 try removing node modules and install again.
After running this command you should see the eslint errors.

I was dealing with the same issue, and nothing seemed to help, even though I did all the configurations correctly, and ESLint was marking the problems in my files correctly.
For me the solution was to move the .vscode folder to the project root.
Now everything works as intended.

Related

How do you reenable esLint squiggly lines after adding Prettier?

Description
I am trying to configure esLint to work with Prettier in VSCode. I am able to successfully install esLint, but when I add Prettier and add it to extends in the esLint config, the squiggly lines provided by esLint disappear. I have provided more details below.
Setup Steps
1. Install esLint and VSCode extension
I installed the esLint VSCode extension, and followed the esLint getting started docs to enable esLint. It works exactly as expected. In this example test code,
console.log("This is a test")
it identifies three issues which is the desired result:
2. Install Prettier and VSCode extension
Next, I installed Prettier and the VSCode extension without any difficulty. In this part of the Prettier Docs, it says I will need to install eslint-config-prettier.
3. Install eslint-config-prettier
This is where the issue occurs. The installation goes fine, but in the eslint-config-prettier github page it says:
Then, add "prettier" to the "extends" array in your .eslintrc.* file. Make sure to put it last, so it gets the chance to override other configs.
{
"extends": [
"some-other-config-you-use",
"prettier"
]
}
The moment I add this to my .eslintrc.json and save the config, the squiggly lines disappear:
I am not sure how to resolve this. I went through the docs for esLint, Prettier, and eslint-config-prettier but none of the optional settings listed in the docs are bringing back the squiggles.
Configurations
.eslintrc.json
{
"env": {
"browser": true,
"es2021": true
},
"extends": [
"airbnb-base",
"prettier"
],
"overrides": [],
"parserOptions": {
"ecmaVersion": "latest",
"sourceType": "module"
},
"rules": {}
}
.prettierrc.json
{
"trailingComma": "es5",
"tabWidth": 4,
"semi": false,
"singleQuote": true
}
esLint Output
[Info - 1:48:20 PM] ESLint server is starting
[Info - 1:48:20 PM] ESLint server running in node v16.14.2
[Info - 1:48:20 PM] ESLint server is running.
[Info - 1:48:21 PM] ESLint library loaded from: /Users/georgeciesinski/Documents/Repositories/todo-list/node_modules/eslint/lib/api.js
Additional Info
My desired behaviour is for esLint to provide the squiggly lines so I can fix the issues manually. At the end, I will run Prettier from the CLI.
I am also using the airbnb eslint config.
I am using an M1 macbook running MacOS Ventura in case this matters.
I was able to find an answer to my query. In short, the configuration works despite my console.log test appearing to fail. The eslint-config-prettier configuration turns off some esLint rules as expected. Per the github docs:
Extending "prettier" turns off a bunch of core ESLint rules, as well as a few rules from these plugins:
#typescript-eslint/eslint-plugin
#babel/eslint-plugin
eslint-plugin-babel
eslint-plugin-flowtype
eslint-plugin-react
eslint-plugin-standard
eslint-plugin-unicorn
eslint-plugin-vue
I was aware of this, but I did not realize that the single quotes and semicolon rules were included in this, both of which stopped working when I extended Prettier. Further testing proved that esLint is in fact linting code that doesn't adhere to the remaining airbnb-base rules which have not been disabled by eslint-config-prettier.

Sublime Text 4 - How To Setup LSP-eslint

When using Sublime text 3 I had SublimeLinter with SublimeLinter-eslint packages, along with eslint & babel-eslint global node modules for JS & JSX syntax.
With the switch to Sublime 4 I decided to give LSP a try. I Installed it, also LSP-css (which ran fine out of the box) & LSP-eslint, which couldn't get to work.
If I check Sublime's status bar I see the language server apparently running (?)
This is within a project with it's own eslintrc.js config file, which works out of the box in VScode. Part of it below:
const RulesAirBnb = require("eslint-config-airbnb-base/rules/best-practices");
const RulesCRA = require("eslint-config-react-app");
module.exports = {
root: true,
parser: "babel-eslint",
parserOptions: {
ecmaVersion: 2018,
sourceType: "module",
ecmaFeatures: {
jsx: true,
generators: true,
},
},
extends: [
"airbnb", // Baseguide is AirBnB"s
"prettier",
"prettier/react",
],
Checked the following SO question but no luck.
How to make it work?
Do I still need global node modules of eslint & babel-eslint? (considering I have both locally under dev dependencies in the package.json of the project - sounds to me I shouldn't)
Installing LSP-typescript did the trick, works out of the box, lsp-eslint not even needed. Unreal.
Found the info here after days of research (thanks chrsap!).
If you are running ST3, check LSP-typescript's readme for needed packages.

ESLint Vue plugin showing false positives for vue/comment-directive

After migrating from VueCLI to Vite, I have to do the linting "manually" as far as I understand; correct me if I'm wrong.
As I only want to lint my .ts and .html files (I separate them even for components), I have this script in my package json:
"lint": "eslint --ext .ts --ext .html src/"
It found some issues like missing :key in loops, but it also shows me this error for each template:
error clear vue/comment-directive
And this is always the closing tag of any root elements within my template.html
If there is only one root element I get one warning for the file, if there are multiple root elements I get a warning for each closing tag.
I don't understand what this rule complains as, according its documentation, it is there for the eslint-disable comments, which I don't have in my templates.
I had the same issue but in nuxt with eslint, i just needed to update eslint-config and eslint-module:
"#nuxtjs/eslint-config": "^5.0.0",
"#nuxtjs/eslint-module": "^3.0.1",
source: https://github.com/nuxt/eslint-plugin-nuxt/issues/121
I've just updated my npm dependencies and I have the same error.
I was reading the eslint documentation and finally I've realized that you can remove the false error if you setup the rule in the .eslintrc.js config file.
this is my .eslintrc.js config file:
module.exports = {
root: true,
env: {
browser: true,
node: true
},
parserOptions: {
parser: 'babel-eslint'
},
extends: [
'#nuxtjs',
'prettier',
'prettier/vue',
'plugin:prettier/recommended',
'plugin:nuxt/recommended'
],
plugins: [
'prettier'
],
// add your custom rules here
rules: {
"vue/comment-directive": 0
}
}
add the rule "vue/comment-directive": 0 and that is!, the error message is removed!.
the possible values are:
0 means disabled
1 means warning
2 means error
Try to change it in your IDE to how it works
(In my case I've had to stop the server and re-run it every time that I've changed a value in this config file.)
I have the same error.
I was taught how to fix this error.
https://qiita.com/tashinoso/items/a72741ca8e2fd928ca77#comment-3e6cd674353056ecbb3a
module.exports = {
...
overrides: [
{
files: ["*.vue"],
processor: "vue/.vue"
}
]
}
Set this snippet on .eslintrc.js
"vue/comment-directive": ["error", {
"reportUnusedDisableDirectives": false
}]
Solve my issue, i wonder why. Solution from documentation
Node v12.20.0
This is a kind of a temporary fix that worked for me and I think it will work for you as well.
vue/comment-directive
This rule is included in all of "plugin:vue/base", "plugin:vue/essential", "plugin:vue/vue3-essential", "plugin:vue/strongly-recommended", "plugin:vue/vue3-strongly-recommended", "plugin:vue/recommended" and "plugin:vue/vue3-recommended".
ESLint doesn't provide any API to enhance eslint-disable functionality and ESLint rules cannot affect other rules. But ESLint provides processors API.
This rule sends all eslint-disable-like comments as errors to the post-process of the .vue file processor, then the post-process removes all vue/comment-directive errors and the reported errors in disabled areas.
All you need to do is add
eslint-disable-next-line vue/component-tags-order
this line as comment above anywhere you using comments within tags in each block you need to specify if comments are added.
For more information please visit:- https://eslint.vuejs.org/rules/comment-directive.html

prettier settings for vscode

I recently switched to a new computer, and am having difficulty with a prettier setting. (I think it's prettier, could be eslint).
This gif illustrates what's happening:
http://g.recordit.co/H871hfT9Sv.gif
Anyone know what this setting is called? I would prefer all imports to be on a single line unless the length extends the printWidth setting.
Here are my relevant User Settings from VS Code:
{
"prettier.printWidth": 100,
"prettier.semi": false,
"prettier.singleQuote": true,
"prettier.trailingComma": "all"
}
Thanks !
Edit:
Visual depiction so you don't need to watch the gif.
Expected:
import React from 'react'
import { Dimensions, StyleSheet, View } from 'react-native'
import LinearGradient from 'react-native-linear-gradient'
import { isIphoneX } from 'react-native-iphone-x-helper'
Behavior: (unwanted)
import React from 'react'
import {
Dimensions,
StyleSheet,
View
} from 'react-native'
import LinearGradient from 'react-native-linear-gradient'
import {
isIphoneX
} from 'react-native-iphone-x-helper'
For those trying to quickly change Prettier settings for VS Code. Here are the steps:
Go to FILE -> PREFERENCES -> SETTINGS. (VS Code Menus)
Settings window should open. Above (Top) there is a search. Type "Prettier"
You should see the available Prettier settings. You can modify them :)
The new way to configure prettier settings:
at the root of your project folder, create a new config file (I'd suggest calling it either ".prettierrc.json" or just ".prettierrc")
in that new file, add json custom settings: my go-to settings for JS are as follows:
{
"trailingComma": "none",
"tabWidth": 4,
"semi": true,
"singleQuote": true
}
I'd suggest doing this in each of your projects and including in any source control, that way every pull of the repo will automatically set some base settings for that developer's instance of prettier.
ctrl + ,
paste --> Prettier: Require Config
uncheck it, then all done.
I had issue with formatting in VSCode. It was taking extension settings from prettier.
I did the following setting ins .vscode/settings.json
created .prettierrc.json file in root of the project
Installed npm install --save-dev prettier
These settings worked for me in vs code.
.vscode/settings.json
{
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true,
"editor.formatOnPaste": false,
"prettier.useEditorConfig": false,
"prettier.useTabs": false,
"prettier.configPath": ".prettierrc.json",
}
.prettierrc.json
{
"trailingComma": "es5",
"tabWidth": 2,
"semi": false,
"singleQuote": true
}
I had a similar issue. To fix this, go into your prettier extension settings and look for "Print Width". Mine was set to '80'. I changed it to '100' and it all fit on one line after I saved the file. You can change the width to whatever you would like.
If Prettier isn't showing up in your VS Code Settings, the extension may have silently crashed, which happens often when settings are changed in multiple places (i.e. tab size was changed in workspace as well as in settings).
Restart VS Code, and search for Prettier again, it should show up this time :)
create .prettierrc file in the project dir, and use following code.
{
"printWidth": 100,
"semi": false,
"singleQuote": true,
"trailingComma": "all"
}
These two steps helped me to set up the .prettierrc file correctly
1- Go to VsCode settings and check formate on save
2- Go to VsCode settings.json and set the defaultFormatter
"editor.defaultFormatter": "esbenp.prettier-vscode"

jshint and sublimelinter settings config on mac

I'm trying to configure sublimelinter, specifically jshint on my Mac. On my windows version of SublimeText there is the following section in SublimeLinter.sublime-settings
"jshint_options":
{
// To fix column positions for JSHint errors you may want to add `"indent": 1` to your
// **User** "jshint_options". This issue affects users with tabs for indentation.
// This fix was reverted due to a conflict with using the `"white": true` option.
// "indent": 1,
"evil": true,
"regexdash": true,
"browser": true,
"wsh": true,
"trailing": true,
"sub": true
},
When I view the file on my Mac this section doesn't exist, is there a place to edit these option on the Mac version without a separate settings file? Or a global settings file for jshint?
I've been digging through similar questions but haven't found a clear solution.
Update:
Actually it doesn't seem to catch any errors at all when using it on the console. My javascript file doesn't end in .js how can I configure it to look at different extensions? I can't find it in the docs.
There's another way to set options globally, without using ".jshintrc" files.
1) create a file with any name (e.g. "jshint.conf"). my file is:
{
"globals": { "$": false },
"globalstrict": true,
"devel": true
}
2) put it anywhere. in my case it is: "c:\Users\Smith\AppData\Roaming\Sublime Text 3\Packages\User\"
3) make the next reference in section "jshint"->"args" of sublime-linter user setting (user/SublimeLinter.sublime-settings):
{
"user": {
"linters": {
"jshint": {
"args": [
"--config", "c:\\Users\\Smith\\AppData\\Roaming\\Sublime Text 3\\Packages\\User\\jshint.conf"
]
}
}
}
}
4) Enjoy!
In general I would recommend against configuring JSHint system-wide. It's usually safer to create a .jshintrc file for each project your work on because it's likely they will have different JSHint requirements.
The jshint_options SublimeLinter setting you mention in your question is from the old version of SublimeLinter, which has recently been reworked to have a simple plugin architecture. The JSHint plugin (which I assume you are using, since the settings you tried didn't work) makes the same recommendation:
You can configure jshint options in the way you would from the command line, with .jshintrc files.
The added benefit of this approach is that you can commit the .jshintrc file to your repository and ensure that anyone who works on the project is working with the same JSHint rules, rather than their own system-wide settings.

Resources