prettier settings for vscode - eslint

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"

Related

eslint rule #nrwl/nx/enforce-module-boundaries fails

Intro
I was very confused with that rule when I recently ported the Ng code base to Nx 12.x. I hope this post helps others who begin migrating from Ng to Nx.
The code base above is a rather small single repo which is now used in production. When using Nx it's a good practice to follow the recommendations for monorepo to be able to use the monorepo benefits in the future as the code base is growing. (E.g. here I'm avoiding the overexposing of the code in the current repo).
I put the code base above into my-org/apps/my-small-repo. By linting I was confused by the failure of the rule #nrwl/nx/enforce-module-boundaries. So I tried different possibilities of mapping the src/app of my-org/apps/my-small-repo where either compiler or linter or both just failed.
I figured out the following solutions.
Solution 1
Just put
"compilerOptions": {
"baseUrl": "src"
},
into the root of apps/my-small-repo/tsconfig.json and replace all of your imports inside of apps/my-small-repo with imports beginning with app.
Example for a DashboardComponent:
import { DashboardComponent } from 'app/components/dashboard/dashboard.component';
Probably a better solution
This solution is tested on nx 13.x, but it probably works on previous versions of nx also.
Put
"app/*": ["apps/my-org/src/app/*"]
to the paths in compilerOptions of your tsconfig.base.json in the repo root. Then put "allowCircularSelfDependency": true, to the rule #nrwl/nx/enforce-module-boundaries in the repo root.
We decided for "allowCircularSelfDependency": true, to avoid working with ugly relative paths like like e.g. this one ../../../../../ in the app. And we also want to have library namespaces in tsconfig.base.json only.
Documentation of the rule
https://github.com/nrwl/nx/blob/master/packages/eslint-plugin-nx/src/rules/enforce-module-boundaries.ts
For those who are coming here without this getting resolved. (nx monorepo usage)
Trouble shooting the 2 errors (TS error and lint error):
First the Alias error:
Cannot find module '#account/components/something' or its corresponding type declarations.
On your base tsconfig.base.json (not tsconfig.json under your apps as it gets overrided), add:
"compilerOptions":{
...
baseUrl:"." // Try "src" as well incase of boiler plates or if your resolved path (on the error) is missing an src.
path: {
"#account/*": ["app/*"],
"#account/components/*": ["app/components/*"]
}
},
The above will resolve:
import { authMiddleware } from '#account/components/something';
from
import { authMiddleware } from '../../../components/something';
For lint error:
Projects should use relative imports to import from other files within the same project - eslint rule #nrwl/nx/enforce-module-boundaries fails`
Add "allowCircularSelfDependency": true.
"#nrwl/nx/enforce-module-boundaries": [
"error",
{
"allowCircularSelfDependency": true, -> This may solve the lint error.
"allow": ["#account/**"], -> // White list the lint error.
...
}
Whitelist the folders: Add "allow": [#foldername]
"#nrwl/nx/enforce-module-boundaries": [
"error",
{
"allow": ["#account/**"], -> // White list the lint error.
...
}
That should fix it.
To get this working:
On your base tsconfig.base.json or your local tsconfig.json.
I suggest to do it on the tsconfig.base.json
Considering your path apps/my-org/src/app/*
"compilerOptions":{
...
baseUrl:"src"
path: {
"#app/*": ["app/*"] // << Here is the change
}
},
Import in your code files from this apps/my-org/src/app/*
to this #app/*

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.

disable jshint for project using Sublime 3

I have a project in which I'm using standard as the default linter, according to sublimeLinter documentation y need to create a .sublime-project file with the following info:
{
"folders":
[
{
"path": "."
}
],
"SublimeLinter":
{
"linters":
{
"jshint": {
"disable": true
}
}
}
}
however this isn't working, I've tried using both disable and #disable, created a .sublimelinterrc file with the same info, also tried with a .sublime-workspacefile, didn't worked, created a .jshintignore... didnt work.
Until now, the only thing that has worked is using this line in top of the file // jshint ignore: start but I don't want to write this in every single file, I want to disable it for all the project. Any idea of how can I do it?
As mentioned by OdatNurd the file won't do nothing by itself, it has to be loaded through the sublime project option in menu.
There is a newer, easier syntax for this. In your sublime project file add the following under settings.
{
"settings":
{
"SublimeLinter.linters.jshint.disable": true
}
}

SublimeLinter ESLint: Lint Whole Project/Directory Instead of Individual File

After an hour+ on Google, I can't believe I haven't found any answers or questions to this. I'm using the SublimeLinter-contrib-eslint package in Sublime Text 3. Is there a way to force SublimeLinter to lint a whole project instead of just one file?
I have a semi-large client-side project with a lot of separate files, and obviously, these files share variables across the window. However, by default, SublimeLinter only lints a single file, so it throws errors that '<variable>' is not defined (no-undef) when another file defines it and '<variable>' is defined but never used (no-unused-vars) when other files use it.
In my .eslintrc, I can set these global variables like this:
"globals": {
"m": true,
"app": true
},
I could also do this in each file, which is arguably good practice anyway:
var m = m || {};
var app = app || {};
But these methods do not fix the unused variable errors.
The best solution I've come up with is to force SublimeLinter to lint the entire directory rather than the individual file. I can't figure out a way to do this though.
I tried turning on the chdir setting in SublimeLinter's user settings:
{
"user": {
...
"linters": {
"eslint": {
"#disable": false,
"args": [],
"excludes": [],
"chdir": "${project}"
}
},
...
}
}
But ^this just sets the $PWD when running eslint, not the arguments passed to eslint.
So is there a way to force SublimeLinter to lint an entire directory (or the whole project)? Is there a better solution to this problem that I haven't thought of? Maybe I'm just spoiled by go fmt.

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