Expected result:
Applied prettier - code formatter in my react project on save.
For example, I hope the semicolon can be automatically added when I save the file.
add semicolon automatically when save
My Problem:
Based on Vscode Output, It seems that prettier has been applied already.
However, the semicolon were not added automatically.
Vscode output about prettier
Dependencies:
prettier: ^1.18.2 / Vscode: 1.73.1 (Universal) / Mac OS
What I have tried:
After searching lots of suggestions online, I have checked these things in VScode.
select default formatter
enable formatting on save & paste
enable prettier
set resolveGlobalModules to false
Setting in my .prettierrc:
{
"useTabs": false,
"singleQuote": true,
"trailingComma": "all",
"printWidth": 80,
"arrowParens": "avoid",
"bracketSpacing": true,
"quoteProps": "as-needed",
"semi": true,
"tabWidth": 2,
"jsxBracketSameLine": false,
"jsxSingleQuote": false
}
Any suggestion would help! Thanks a lot.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 months ago.
Improve this question
I am currently working on a TypeScript project on VS Code. To save time and to have a better formatted code directly as I am used to write, I configured eslint and prettier on the project (and on VS Code).
Here is the problem, at the beginning eslint was indicating the errors according to the rules I had specified. Then I wanted to set up prettier which ended up working according to the rules I gave it. I had to fight a little bit to make that VS understand prettier is the default formatter and so it had to format my files on save. Once I managed to do that, I was happy to see that some of my files that had bad formatting (due to it being a group project that different people worked on) now had a clean display and the code was cleaned up a bit at the same time.
Unfortunately, it would have been too easy if it had just worked that way. For some reason, since I set the on save formatting, it consistently brings up my else on the end brace if line. So instead of having :
if (...) {
...
}
else {
...
}
I have this:
if (...) {
...
} else {
...
}
It bothers me a bit, I've always been used to the format above, I find it more readable. Maybe I'm not very lucid, but I still haven't managed to find a way to prevent this when I save (I searched for configurations in VS Code, prettier and eslint). Idk exactly where does it come from and I can't get it to keep the line break after the brace just before the else.
My .prettierrc file
{
"printWidth": 170,
"tabWidth": 2,
"useTabs": true,
"singleQuote": false,
"semi": true,
"trailingComma": "none"
}
My .eslint.js file
export default {
parser: "#typescript-eslint/parser",
plugins: [
"#typescript-eslint",
"import"
],
env: {
commonjs: true,
es2020: true,
node: true
},
extends: [
"eslint:recommended",
"plugin:import/recommended",
"plugin:import/typescript"
],
parserOptions: {
ecmaVersion: 11
},
rules: {
"no-else-return": "warn",
"no-case-declarations": "off",
eqeqeq: "error",
"no-var": "warn",
"prefer-const": "off",
"import/no-commonjs": "warn",
"no-unused-vars": "off",
"padding-line-between-statements": [
"error",
{ blankLine: "always", prev: "block-like", next: "block-like" }
]
}
};
.vscode > settings.json :
{
"editor.formatOnSave": false,
"[typescript]": {
"editor.formatOnSave": true
},
"editor.defaultFormatter": "esbenp.prettier-vscode"
}
Current package.json
(I updated the packages today to see if it changed anything, they already "worked" before as they do now
prettier was 2.6.2
eslint was 7.32.0)
"dependencies": {
...
"prettier": "^2.7.1",
...
},
"devDependencies": {
...
"#typescript-eslint/eslint-plugin": "^5.19.0",
"#typescript-eslint/parser": "^5.19.0",
"eslint": "^8.22.0",
"eslint-plugin-import": "^2.26.0",
...
}
eslint > Code Actions On Save: Rules > settings.json
{
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[html]": {
"editor.defaultFormatter": "vscode.html-language-features"
},
"editor.detectIndentation": false,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true,
"typescript.format.enable": false,
"javascript.format.enable": false,
"typescript.format.placeOpenBraceOnNewLineForControlBlocks": true,
"javascript.format.placeOpenBraceOnNewLineForControlBlocks": true,
"eslint.format.enable": true,
"eslint.codeActionsOnSave.rules": null
}
I have the impression that there is a kind of desynchronization between VS Code settings in UI mode and VS Code settings manually specified in code via .json file
If I'm not talking nonsense, eslint is only supposed to inform me of errors and warnings related to the rules I gave it, nothing more. However, there is an eslint formatter, but how is it configured and how does it work? Is that the problem here?
In summary :
I want to prevent the else from coming up on the end line of the if (next to the brace) when I save and prettier formats my files
Thanks to all those who will take the time to read
And thank you to those who might be able to help me
Btw, if you have any suggestions for
cool eslint or prettier rules,
some VS Code extensions that can be useful,
some VS Code useful settings
Let me know :D
I am using Eslint: v7.26.0 and have the following rule added to it:
'react/sort-prop-types': [
2,
{
callbacksLast: true,
ignoreCase: false,
requiredFirst: true,
sortShapeProp: true,
noSortAlphabetically: false,
},
],
However, when I run the command to fix the ESLint issues, the issues thrown by this rule are not auto-fixed.
eslint --fix --format table someFile.js
Is there a way to auto-fix the errors thrown by this rule?
Sadly, this rule is not auto-fixable.
You can check the list of all the supported rules here.
It also tells you if the rule fixable with eslint --fix and if it is enabled by default.
If you are using VSCode and have installed the ESLint extension, then it will show you all the errors during active development which you can then fix.
The only con of this is that you will have to manually fix the errors if you are in the middle of development
sort-prop-types autofixer does sort within the spread boundaries:
I think this is expected.
https://github.com/yannickcr/eslint-plugin-react/blob/4a72e6a0784f7cc7f16f4574ce7f14de55540a73/tests/lib/rules/sort-prop-types.js#L1007-L1037
I traying setup my vim based typescript developing environment, but have an issue with indent management.
Probably 'eslint' says: indent: Expected indentation of 2 spaces but found 4. after prettier reformat.
My .eslintrc.js:
module.exports = {
parser: '#typescript-eslint/parser', // Specifies the ESLint parser
extends: [
'plugin:react/recommended', // Uses the recommended rules from #eslint-plugin-react
'plugin:#typescript-eslint/recommended', // Uses the recommended rules from #typescript-eslint/eslint-plugin
'prettier/#typescript-eslint',
'plugin:prettier/recommended',
],
parserOptions: {
ecmaVersion: 2018, // Allows for the parsing of modern ECMAScript features
sourceType: 'module', // Allows for the use of imports
ecmaFeatures: {
jsx: true, // Allows for the parsing of JSX
tsx: true, // Allows for the parsing of TSX ???
},
},
rules: {
indent: ['error', 2],
quotes: ['error', 'single'],
semi: ['error', 'never'],
'sort-keys': ['error', 'asc', { caseSensitive: true, natural: false }],
},
}
My .prettierc:
module.exports = {
semi: false,
trailingComma: 'all',
singleQuote: true,
printWidth: 80,
tabWidth: 2,
};
As per this Kai Cataldo's comment on this GitHub issue:
ESLint's indent rule and Prettier's indentation styles do not match - they're completely separate implementations and are two different approaches to solving the same problem ("how do we enforce consistent indentation in a project").
Therefore, when using prettier, you'd better disable eslint's indent rule. It's guaranteed that they will clash.
This should fix it https://github.com/prettier/eslint-config-prettier
It disables rules in eslint that conflict with prettier
in eslintrc add indent: [2, 2, { SwitchCase: 1}]
Parameters defined
new eslint rules want the first parameter to be a number: Severity should be one of the following: 0 = off, 1 = warn, 2 = error.
the amount of indent
The object is stating how to indent switch and case statements following the options here.
Turning off default Visual Studio Code parser and just leaving the eslint parser on save fixed it for me.
Just go to settings Ctrl/Cmd + ,, choose User (global settings) or Workspace (only for the working repo) and on top right corner click the paper with a turning arrow. That will open the declared settings on a json file. With the following settings it should work on any case:
{
// other settings
"editor.formatOnSave": false,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true,
"source.organizeImports": false
},
// other settings
}
Normally at the bottom of the Visual Studio Code window you have a Fix on save: X flag. That should be linked with this setting so make sure to leave it consistent.
I ran into the same issue. Thing is you can just manually override any clashing rules. In my case it was the prettier/prettier plugin for ESLint, so that can be solved adding the indent rule, under the required plugin.
"rules": {
// "indent":["error",10]
"prettier/prettier":[ //or whatever plugin that is causing the clash
"error",
{
"tabWidth":4
}
]
}
You can override specific rules like this, to get rid of any clashes.
Most annoying thing.. so fixed with: eslint-config-prettier
{
"rules": {
"no-tabs": ["error", {"allowIndentationTabs": true}]
}
}
eslint-config-prettier will disable all ESLint formatting rules that may conflict with Prettier's rules.npm i --save-dev eslint-config-prettier
eslint-plugin-prettier is the plugin that will add Prettier's formatting rules.
Let's tell ESLint we'll use Prettier's recommended configuration:
npm i --save-dev eslint-plugin-prettier
//eslintrc.js
{
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest",
"plugin:prettier/recommended"
]
}
It seems on my end, the only conflict is with ternary operations. Another option to fix the issue is to use the following eslint rule.
"indent": ["error", 2, { "offsetTernaryExpressions": true }],
There are a lot more options here: https://eslint.org/docs/latest/rules/indent#offsetternaryexpressions
I find eslint's indent rules more configurable and would use them over prettier.
I had this issue and by changing Prettier to Use Tabs in the settings menu (ctrl + shift + P), it fixed the issue for me.
In my case I just changed CRLF (Carriage Return, Line Feed) to LF (Line Feed) on VSCode
If you are using VS-Code and configured the eslint and prettier settings as per the others answers here, then also check this option in VS-Code ;)
Change it to 'Tab' instead.
In my case what I did was I removed the indentation rule from the .eslintrc file and added useTabs: true to my .prettierrc file.
After reloading the VS Code it works perfectly with the tab size indentation.
So, npm i --save-dev eslint-config-prettier fixed the Issue as pointed out by Akshay
Background
I just get into learning react.js, and find out a lot people are using prettier and eslint to format their code. But after I setup my own based on the online guides, wired things happened. It can format code correctly when I'm saving the file, but not when I manually trigger format function (Shift+option+F). It will format the file to a wired way that eslint will give me errors.
Here's the vscode settings that I'm using:
"editor.formatOnSave": true,
"[javascript]": {
"editor.formatOnSave": false
},
"eslint.autoFixOnSave": true,
"eslint.alwaysShowStatus": true,
"prettier.disableLanguages": [
"js"
],
"editor.detectIndentation": true,
"editor.tabSize": 2,
and I also have a .eslintrc file
{
"extends": ["react-app", "plugin:prettier/recommended"],
}
and a .prettierrc file
{
"trailingComma": "es5",
"tabWidth": 2,
"semi": true,
"singleQuote": true,
"jsxBracketSameLine": true
}
What I assume here is the vscode keyboard shorcut(Shift+option+F) is not using the same configuration (or even not the same tool) as autoFixOnSave.
But also I don't understand how these tools work and integrated together, and which one overrides which one. Can some one help?
Why are you disabling js for prettier?
Do you know Prettier can be integrated flawlessly with ESLint?
Take a look at this article: Prettier: Integrating with ESLint
In your user/workspace settings, just add:
"files.autoSave": "off",
"editor.formatOnSave": true,
"eslint.autoFixOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll": true,
"source.organizeImports": true
},
"eslint.options": {
"extensions": [".js", ".jsx"]
},
"eslint.validate": ["javascript", "javascriptreact", "typescript", "typescriptreact"],
Also it is recommended having a .editorconfig in your root folder:
# http://editorconfig.org
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = crlf
insert_final_newline = true
trim_trailing_whitespace = true
[*.md]
max_line_length = off
trim_trailing_whitespace = false
And finally, in your .eslintrc file, add:
"extends": ["react-app", "plugin:prettier/recommended", "prettier/react"],
Check out the eslint-plugin-react for validating react.
I am not looking at the mac version of VS code, but I think that hotkey is supposed to be Shift + Option + F
Edit: I usually disable the default javascript formatter in vscode, because it can conflict with my eslint rules, which makes it impossible for eslint to properly format my code.
ESLint has it's own Fix command which does not have a hotkey on my setup, but I have eslint.autoFixOnSave: true.
Prettier does not hook into the internal vscode format command. It also has it's own command set up. The default hotkey to run prettier format for the majority of the available prettier extensions is CMD + Shift + P -> Format Document but will trigger on save if editor.formatOnSave is true.
I would like to lint html angular template files via the command line, similar to:
ng lint
I would like to validate the Angular html templates to check they are valid and the variables are correct, so I can run this in a CI pipeline like Travis or AWS Codebuild.
Visual studio code runs Angular Language Services and can do this:
What I want is to capture these errors, so that I don't let invalid Angular html templates get into releases.
How can I achieve this?
What you are seeing here is in fact a Typescript error, not a lint error.
There is an option fullTemplateTypeCheck that allows you to capture such errors during build when AOT is activated:
This option tells the compiler to enable the binding expression validation phase of the template compiler which uses TypeScript to validate binding expressions.
This option is false by default.
Note: It is recommended to set this to true because this option will default to true in the future.
This can in fact slow down your build considerably, so what you can do if you only want to use this in the CI pipeline:
Create a new tsconfig.strict.json next to your tsconfig.app.json like this:
{
"extends": "./tsconfig.app.json",
"angularCompilerOptions": {
"fullTemplateTypeCheck": true,
"strictInjectionParameters": true
}
}
In angular.json add a new configuration "strictProd" under projects>YourProject>architect>build>configurations that looks like this:
"strictProd": {
"tsConfig": "src/tsconfig.app.strict.json",
"aot": true
[...your other prod settings here],
}
Run it with ng build -c strictProd
The best thing I have found is the html hint node package. You can read about it here: https://htmlhint.com/docs/user-guide/getting-started
Here is settings for the .htmlhintrc that work with Angular.
{
"tagname-lowercase": true,
"attr-lowercase": false,
"attr-value-double-quotes": true,
"attr-value-not-empty": false,
"attr-no-duplication": true,
"doctype-first": false,
"tag-pair": true,
"tag-self-close": true,
"empty-tag-not-self-closed": true,
"spec-char-escape": false,
"id-unique": false,
"src-not-empty": true,
"title-require": true,
"alt-require": true,
"doctype-html5": true,
"id-class-value": "true",
"style-disabled": true,
"inline-style-disabled": true,
"inline-script-disabled": true,
"space-tab-mixed-disabled": "true",
"id-class-ad-disabled": true,
"href-abs-or-rel": false,
"attr-unsafe-chars": true,
"head-script-disabled": true
}