Why is Prettier not including trailing commas? - javascript

I've created a completely new angular application using ng new test-app, added Prettier to devDependencies and installed it and have disabled all extensions except Prettier in VSCode.
The problem is that when I set up VSCode to format on save, it always removes the trailing commas in typescript arrays and objects.
I've set "trailingComma":"all" in .prettierrc.json as well as having these settings in settings.json
{
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnPaste": true,
"editor.formatOnSave": true,
"prettier.trailingComma": "all",
"prettier.proseWrap": "always",
"prettier.useEditorConfig": false,
"javascript.updateImportsOnFileMove.enabled": "always",
"typescript.updateImportsOnFileMove.enabled": "always"
}
My User settings for all vscode projects is
{
"git.autoStash": true,
"todo-tree.general.tags": [
"BUG",
"HACK",
"FIXME",
"TODO",
"XXX",
"[ ]",
"[x]"
],
"todo-tree.regex.regex": "(//|#|<!--|;|/\\*|^|^\\s*(-|\\d+.))\\s*($TAGS)",
"git.autofetch": true,
"files.autoSave": "afterDelay",
"git.enableSmartCommit": true,
"workbench.startupEditor": "newUntitledFile",
"cSpell.userWords": [
"Reorderable",
"configcat",
"datatable",
"devkit",
"initialise",
"initialising",
"primeng"
],
"editor.largeFileOptimizations": false,
"git.confirmSync": false,
"diffEditor.wordWrap": "on",
"explorer.confirmDelete": true,
"explorer.confirmDragAndDrop": true,
"workbench.editorAssociations": {
"*.sqlite": "default"
},
"diffEditor.ignoreTrimWhitespace": false
}

Turns out Prettier does add trailing comma's but only if the array is split over multiple lines.
E.g. the code below will have a trailing comma added by prettier
let x = [
"aaaaaaaaaaaaaaaa",
"bbbbbbbbbbbbbbbb",
"cccccccccccccccc",
"dddddddddddddddd",
"eeeeeeeeeeeeeeee",
"ffffffffffffffff"
];

Related

Not working in prettier formatting using monaco editor

I'm trying to make an IDE that works in the browser using the Monaco editor. I wanted to use Prettier for a nice formatting. It only works for Javascript files or only html files. However, it does not work on files of the types I have specified below. How can I fix.
Expected :
Result :
Also i am getting this error :
monaco.languages.registerDocumentFormattingEditProvider("javascript", {
async provideDocumentFormattingEdits(model) {
alert(1);
var text1 = prettier.format(model.getValue(), {
wrapAttributes: "force",
parser: "babel",
// plugins: [babel],
htmlWhitespaceSensitivity: "ignore",
arrowParens: "always",
bracketSpacing: true,
endOfLine: "lf",
insertPragma: false,
singleAttributePerLine: false,
bracketSameLine: false,
printWidth: 400,
proseWrap: "preserve",
quoteProps: "as-needed",
requirePragma: false,
semi: true,
singleQuote: true,
tabWidth: 4,
//trailingComma: 'es5',
useTabs: false,
vueIndentScriptAndStyle: false,
});
return [
{
range: model.getFullModelRange(),
text: text1,
},
];
},
});
monaco_scr_editor = monaco.editor.create(document.getElementById("browserIDE"), {
value: ["<html>Please Wait Loading</html>"].join("\n"),
language: "javascript",
theme: "vs-dark",
wrappingColumn: 0,
autoIndent: true,
formatOnPaste: true,
formatOnType: true,
wrappingIndent: "indent",
wordWrap: "off",
automaticLayout: true,
overviewRulerLanes: 1,
overviewRulerBorder: true,
minimap: { enabled: false },
});
You need to provide right value for options.parser.
From docs
options.parser must be set according to the language you are formatting (see the list of available parsers). Alternatively, options.filepath can be specified for Prettier to infer the parser from the file extension.
so set it to parser: "html".
It seems like designed to use pre-defined formatter.
Please refer this issue : Disable default formatters.
I tested code as below(from a thread),
monaco.languages.html.htmlDefaults.setModeConfiguration({
...monaco.languages.html.htmlDefaults.modeConfiguration,
documentFormattingEdits: false,
documentRangeFormattingEdits: false,
});
This will work for you.
But you still get error relate with prettier.
Refer this issue : https://github.com/prettier/prettier/issues/6264
Before doing this, install this to make easy import parser list from node_module.
npm install #types/prettier
and then import it.
import * as prettier from 'prettier/standalone'
import * as parserHtml from 'prettier/parser-html'
...
prettier.format(model.getValue(), {
...
parser: "html",
plugins: [parserHtml],
...

Invalid configuration for rule "react/jsx-sort-props"

I'm trying to sort props names alphabetically using the plugin eslint-plugin-react but I'm getting this error:
[Error ] .eslintrc.json: Configuration for rule "react/jsx-sort-props" is invalid: Value {"callbacksLast":true,"shorthandFirst":false,"shorthandLast":true,"multiline":"last","ignoreCase":true,"noSortAlphabetically":false} should NOT have additional properties.
This is my .eslintrc.json file:
{
"extends": [
"eslint:recommended",
"plugin:react/recommended",
"next/core-web-vitals"
],
"rules": {
"react/jsx-sort-props": [
"2",
{
"callbacksLast": true,
"shorthandFirst": false,
"shorthandLast": true,
"multiline": "last",
"ignoreCase": true,
"noSortAlphabetically": false
}
]
}
}
What I'm missing?
There are two issues:
The severity option, if you're using a number, should be a number, not a string that contains a number - 2, not "2". (Though, personally, I'd suggest using "error" instead - it makes it clearer from reading the config what the rule means for your project - "error" makes more intuitive sense than 2)
There is a bug in the linter rule's jsx-sort-props.js - although the docs reference a multiline property, said property does not exist anywhere in the lint rule implementation, and so an error is thrown when you pass in an object containing that property. Remove it.
"rules": {
"react/jsx-sort-props": [
2,
{
"callbacksLast": true,
"shorthandFirst": false,
"shorthandLast": true,
"ignoreCase": true,
"noSortAlphabetically": false
}
]
}

Visual Studio Code is auto formatting my js file that has markup

I upgraded my visual studio code version 1.33.0 recently and am having issues with saving my files because they keep formatting when I save the document.
I have looked through the update - https://code.visualstudio.com/updates/v1_33 and opened up the javascript and javascriptreact languages in the settings.json file.
settings.json file
{
"window.zoomLevel": 0,
"files.associations": {
"*.scss": "scss"
},
"mssql.connections": [
{
"server": "localhost",
"database": "",
"authenticationType": "SqlLogin",
"user": "SA",
"password": "",
"emptyPasswordInput": false,
"savePassword": true,
"profileName": "localhost profile"
}
],
"javascript.implicitProjectConfig.experimentalDecorators": false,
"editor.tabSize": 2,
"php.validate.enable": false,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"workbench.startupEditor": "none",
"javascript.format.insertSpaceBeforeFunctionParenthesis": true,
"editor.formatOnSave": false,
"[javascript]": {
"editor.formatOnSave": false,
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[javascriptreact]": {
"editor.formatOnSave": false,
"editor.defaultFormatter": "esbenp.prettier-vscode"
}
}
This does not matter, it ignores these preferences and auto formats it to VSCs auto default format. I am using .js files with react and switching the rsx is not an option. Thanks
There are 3 levels of settings(User level, Workspace Level, Global) in VSC. Check if formatOnSave is false for all of them.
If it still indents your code, then create a .editorconfig file in your project and mention your settings there. It gets the highest preference in VSC settings and will override all the others.

Possibility for nested properties in stylelint in Gulp?

Is it possible to have a nested property list and let do stylelint it's work? I tried to do this, but I got the following error:
events.js:85
throw er; // Unhandled 'error' event
^
Error: Expected pseudo-class or pseudo-element
I tried it with this code:
padding: {
left: 20px;
top: 30px;
}
And this is the configuration I use at the moment:
"rules": {
"block-no-empty": true,
"color-no-invalid-hex": true,
"declaration-colon-space-after": "always",
"declaration-colon-space-before": "never",
"function-comma-space-after": "always",
"function-url-quotes": "double",
"media-feature-colon-space-after": "always",
"media-feature-colon-space-before": "never",
"media-feature-name-no-vendor-prefix": true,
"max-empty-lines": 5,
"number-leading-zero": "never",
"number-no-trailing-zeros": true,
"property-no-vendor-prefix": true,
"rule-no-duplicate-properties": true,
"declaration-block-no-single-line": true,
"rule-trailing-semicolon": "always",
"selector-list-comma-space-before": "never",
"selector-list-comma-newline-after": "always",
"selector-no-id": true,
"string-quotes": "double",
"value-no-vendor-prefix": true
}
Or is there another SCSS linter without using Ruby gems?
It might be useful to have this information:
These are my vars:
var postcss = require('gulp-postcss');
var reporter = require('postcss-reporter');
var syntax_scss = require('postcss-scss');
var stylelint = require('stylelint');
And at the bottom of the file is this:
var processors = [
stylelint(stylelintConfig),
reporter({
clearMessages: true,
throwError: false
})
];
gulp.src('style.scss')
.pipe(postcss(
processors, {
syntax: syntax_scss
}));
I followed a tutorial like this one:
http://www.creativenightly.com/2016/02/How-to-lint-your-css-with-stylelint/
And changed some bits in my code to work with the rest of the website.
This issue is due to the code not being valid css but is valid for scss.
Related: https://github.com/stylelint/stylelint/issues/1386#issuecomment-223266044

gulp-jscs Object.keys called on non-object

I'm a novice at gulp, and trying to play with it. I get this error when I try to use gulp-jscs
'default' errored after 98 ms
[16:58:00] TypeError: Object.keys called on non-object
at Function.keys (native)
at NodeConfiguration.Configuration._throwNonCamelCaseErrorIfNeeded (/home/kbadr/Node_Projects/demo/membership/node_modules/gulp-jscs/node_modules/jscs/lib/config/configuration.js:440:12)
at NodeConfiguration.Configuration.load (/home/kbadr/Node_Projects/demo/membership/node_modules/gulp-jscs/node_modules/jscs/lib/config/configuration.js:51:10)
at StringChecker.configure (/home/kbadr/Node_Projects/demo/membership/node_modules/gulp-jscs/node_modules/jscs/lib/string-checker.js:66:29)
at Checker.configure (/home/kbadr/Node_Projects/demo/membership/node_modules/gulp-jscs/node_modules/jscs/lib/checker.js:26:39)
at module.exports (/home/kbadr/Node_Projects/demo/membership/node_modules/gulp-jscs/index.js:31:11)
at Gulp.<anonymous> (/home/kbadr/Node_Projects/demo/membership/gulpfile.js:22:15)
at module.exports (/home/kbadr/Node_Projects/demo/membership/node_modules/gulp/node_modules/orchestrator/lib/runTask.js:34:7)
at Gulp.Orchestrator._runTask (/home/kbadr/Node_Projects/demo/membership/node_modules/gulp/node_modules/orchestrator/index.js:273:3)
at Gulp.Orchestrator._runStep (/home/kbadr/Node_Projects/demo/membership/node_modules/gulp/node_modules/orchestrator/index.js:214:10
and here's my gulpfile
var gulp = require('gulp');
var jscs = require('gulp-jscs');
gulp.task('default', function () {
return gulp.src('src/app.js')
.pipe(jscs());
});
This seems to happen if jscs doesn't have read access to your .jscsrc or if it doesn't exist. This happened to me after copying and pasting it from an old git repro. To fix this open the file with a text editor and resave it, accepting the prompt to overwrite as well as starting with a '.' (e.g. .jscsrc) Run your task again and it will complete.
I had the same problem: "Unable to load JSCS config file at /Desktop/node/My_Project_Name/.jscsrc
Unexpected end of input...."
I was able to solve the problem by first checking to see if the file existed in the root of my project. in terminal run this command:
ls -ld .?*
The file was never created for me so I created the .jscsrc file then I added the following code:
{
"excludeFiles": ["node_modules/**", "bower_components/**"],
"requireCurlyBraces": [
"if",
"else",
"for",
"while",
"do",
"try",
"catch"
],
"requireOperatorBeforeLineBreak": true,
"requireCamelCaseOrUpperCaseIdentifiers": true,
"maximumLineLength": {
"value": 100,
"allowComments": true,
"allowRegex": true
},
"validateIndentation": 4,
"validateQuoteMarks": "'",
"disallowMultipleLineStrings": true,
"disallowMixedSpacesAndTabs": true,
"disallowTrailingWhitespace": true,
"disallowSpaceAfterPrefixUnaryOperators": true,
"disallowMultipleVarDecl": null,
"requireSpaceAfterKeywords": [
"if",
"else",
"for",
"while",
"do",
"switch",
"return",
"try",
"catch"
],
"requireSpaceBeforeBinaryOperators": [
"=", "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=",
"&=", "|=", "^=", "+=",
"+", "-", "*", "/", "%", "<<", ">>", ">>>", "&",
"|", "^", "&&", "||", "===", "==", ">=",
"<=", "<", ">", "!=", "!=="
],
"requireSpaceAfterBinaryOperators": true,
"requireSpacesInConditionalExpression": true,
"requireSpaceBeforeBlockStatements": true,
"requireLineFeedAtFileEnd": true,
"disallowSpacesInsideObjectBrackets": "all",
"disallowSpacesInsideArrayBrackets": "all",
"disallowSpacesInsideParentheses": true,
"validateJSDoc": {
"checkParamNames": true,
"requireParamTypes": true
},
"disallowMultipleLineBreaks": true,
"disallowCommaBeforeLineBreak": null,
"disallowDanglingUnderscores": null,
"disallowEmptyBlocks": null,
"disallowMultipleLineStrings": null,
"disallowTrailingComma": null,
"requireCommaBeforeLineBreak": null,
"requireDotNotation": null,
"requireMultipleVarDecl": null,
"requireParenthesesAroundIIFE": true
}
Save this file to the root of your project, then run the gulp task command again it should work.
Updated the dependency in bower.json on ngCordova and resolved the issue !!!

Categories