Sublime Text 4 - How To Setup LSP-eslint - 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.

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.

ESLint in VSCode not fixing on save

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.

Eslint does not recognize private field declaration using nodejs 12

Eslint will not recognize private fields marked with # in class declarations, even though I'm using NodeJS version 12 (which supports them).
I am running NodeJS v12.7.0. I have searched all DuckDuckGo and Google and I cannot find a plugin or option in eslint which will tell it to accept the private field notation (#). I have emca set to version 10.
class MyClass {
#foo = 'bar';
#bar = 'foo';
constructor(foo, bar) {
this.#foo = foo;
this.#bar = bar;
}
...
};
When I run eslint on the above code, I get:
2:3 error Parsing error: Unexpected character '#'
The project I'm working on does not use Babel, and I don't want to have to include it just to make private fields work. Any ideas how to make this work without having to resort to using Babel?
(Nothing against Babel of course, it's just on this particular project I don't want it).
2021 Update: You do not need babel for this anymore!
You can simply update eslint to v8.0.0 and above.
See eslint release notes: https://eslint.org/blog/2021/10/eslint-v8.0.0-released#highlights
Make sure this is in your .eslintrc file or similar:
{
"parserOptions": {
"ecmaVersion": 13
}
}
You can also just use latest instead of specifically version 13.
The upvoted answer is a little out of date, the babel-eslint package has changed, also, you need to make sure you have Babel configured too, in my case I was on a server, so it wasn't.
I blogged about the solution here:
https://dev.to/griffadev/setting-up-eslint-to-work-with-new-or-proposed-javascript-features-such-as-private-class-fields-5fm7
TL;DR:
npm i eslint #babel/core #babel/eslint-parser #babel/preset-env -D
Example .eslintrc
{
"env": {
"browser": true,
"es2021": true,
"node": true
},
"extends": "eslint:recommended",
"parser": "#babel/eslint-parser",
"parserOptions": {
"ecmaVersion": 12,
"sourceType": "module"
},
"rules": {
}
}
Configure .babelrc
{
"presets": [
["#babel/preset-env",
{
"shippedProposals": true
}]
]
}
If you are using Jest and you don't have a .babelrc configured already, it will start picking up this new file, this may be a problem.
You can workaround this by renaming the .babelrc file to something else, and updating eslint config file:
"babelOptions": {
"configFile": "./.babel-eslintrc"
}
I think that you might have to bite the bullet and use babel-eslint: https://github.com/babel/babel-eslint, which requires that you install babel/core#>=7.2.0
Even though the private class fields are included in node 12, it's still a Stage 3 experimental feature according to the spec (as of August 2019)
npm install eslint babel-eslint --save-dev
# or
yarn add eslint babel-eslint -D
and add
"parser": "babel-eslint",
to your .eslintrc.js file
In regards to Visual Studio 2019, I found that the #babel/eslint-parser doesn't work with it but the older babel-eslint does. Other set up per #George's answer.
Visual Studio 2019 version as at time of answer: 16.9.5
Unless you really, really want that specific file linted I would avoid adding new dependencies just to make tests pass. My advice in this case would be to add
ignorePatterns: ["path/to/file(s).js"],
in your .eslintrc.js file. That will avoid linting that specific file. If you really want to lint it, do a substitution of # by __, lint, and change it back. I know, it's a hack, but it does not introduce any kind of dependency and it works.

Angular 6 and karma 'Can not load "#angular-devkit/build-angular", it is not registered'

I had to migrate to the newest angular version. After that, karma tests stopped working and just keep crushing with an error log:
14 04 2018 14:17:00.453:ERROR [preprocess]: Can not load "#angular-devkit/build-angular", it is not registered!
Perhaps you are missing some plugin?
...\parkandrest-ui\node_modules\#angular-devkit\build-angular\src\angular-cli-files\plugins\packages\angular_devkit\build_angular\src\angular-cli-files\plugins\karma.ts:52
const options = config.buildWebpack.options;
^ TypeError: Cannot read property 'options' of undefined
at init (...\parkandrest-ui\node_modules\#angular-devkit\build-angular\src\angular-cli-files\plugins\packages\angular_devkit\build_angular\src\angular-cli-files\plugins\karma.ts:52:39)
at Array.invoke (...\parkandrest-ui\node_modules\di\lib\injector.js:75:15)
at Injector.get (...\parkandrest-ui\node_modules\di\lib\injector.js:48:43)
at E:\Workspace\Training\spring-boot-tutorial\parkandrest-ui\node_modules\karma\lib\server.js:166:20
at Array.forEach ()
at Server._start (...\parkandrest-ui\node_modules\karma\lib\server.js:165:21)
at Injector.invoke (...\parkandrest-ui\node_modules\di\lib\injector.js:75:15)
at Server.start (...\parkandrest-ui\node_modules\karma\lib\server.js:126:18)
at Object.
My karma.conf.js file looks like this:
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '#angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('#angular-devkit/build-angular/plugins/karma')
],
client:{
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
files: [
{ pattern: './src/test.ts', watched: false }
],
preprocessors: {
'./src/test.ts': ['#angular-devkit/build-angular']
},
mime: {
'text/x-typescript': ['ts','tsx']
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, 'coverage'), reports: [ 'html', 'lcovonly' ],
fixWebpackSourcePaths: true
},
angularCli: {
config: './angular.json',
environment: 'dev'
},
reporters: config.angularCli && config.angularCli.codeCoverage
? ['progress', 'coverage-istanbul']
: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false
});
};
#angular-devkit\build-angular is of course installed. I appreciate any help.
EDIT:
I have a solution which actually combines most of the user answers to my question with my own. Firstly I updated my whole project to stable angular 6 release. Next, I generated empty project like #R.Richards suggested and then I replaced almost every configuration in my old project with the new one. Finally, I have encountered a problem #Suvendu warn me about. I used his solution to resolve it. Unfortunately, I still have one problem with my environment (Intellij IDEA 2017.3.4 Ultimate) which disallows me to start karma tests directly from my IDE ( I've got the same error #Suvendu mentions about), however, it is a topic for the next question.
My solution was a little different, as I had to move the karma.conf.js.
Update all dependencies and make sure the app itself works as intented
If not done already: Replacing every occurrence of #angular/cli with #angular-devkit/build-angular in the karma.conf.js
Removing the files and the preprocessor configs from the karma.conf.js completely. This is all defined in the angular.json and should be handled automatically by the #anguler-devkit karma plugin.
Could not find module "#angular-devkit/build-angular"
here is what worked for my project:
npm install -g #angular/cli
npm install #angular/cli
ng update #angular/cli --migrate-only --from=1.7.0
ng update #angular/core
npm install rxjs-compat
ng serve
I hope this works for you!
I followed this guide to do a clean migration of the project, which solved the same issue for me.
Try installing karma-webpack with npm and then add it to the plugins array -
plugins: [
...
require('karma-webpack'),
...
],
and replace the preprocessors with this -
preprocessors: {
'./src/test.ts': ['webpack']
},
This worked in my case and will also work for the below anticipated future error-
Error: The '#angular-devkit/build-angular/plugins/karma' karma plugin is meant to be used from within Angular CLI and will not work correctly outside of it.
Hope this helps.
The solution for me was that my NODE_ENV environmental variable was set to "production". While trying to upgrade to Angular 6 I did not realize that #angular-devkit/build-angular was listed in my devDependencies, which are not installed in a production environment.
Running "unset NODE_ENV" and removing NODE_ENV from /etc/environment fixed my problem. (Note: Be careful changing this variable in an actual production environment).
In your karma.conf.js add following library, in plugins section. This is done in Angular8.
require('#angular-devkit/build-angular/plugins/karma')

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