When I copy an API response to a js file in vscode, it puts everything in double quotes - visual-studio-code

In chrome devtools, when I hover over the preview of a response from a REST API call and click 'copy value', then I paste that value in a json file, it looks as I expect. When I paste that value in a js file, it does not look like I expect. What this is 'supposed' to look like may be irrelevant, I NEED it to look like test-file.json for it to work in my tests. I do not see a prettier rc config file.
Ex) test-file.json
{
type: 'mover',
id: 888,
organization_id: null
}
Ex) test-file.js
{
"type": "mover",
"id: 888,
"organization_id: null
}
I do not want prettier or vscode to put the key in my key value pair in double quotes. It should have no quotes. This doesn't work unless I painstakingly manually edit it.
My settings json looks like this:
{
"redhat.telemetry.enabled": true,
//"editor.codeActionsOnSave": {
// "source.fixAll.eslint": true
//},
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[json]": {
"editor.defaultFormatter": "vscode.json-language-features"
},
"git.confirmSync": false,
"git.ignoreRebaseWarning": true,
"[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"diffEditor.ignoreTrimWhitespace": false,
"terminal.integrated.profiles.linux": {
"bash": {
"path": "bash",
"icon": "terminal-bash"
},
"zsh": {
"path": "zsh"
},
"fish": {
"path": "fish"
},
"tmux": {
"path": "tmux",
"icon": "terminal-tmux"
},
"pwsh": {
"path": "pwsh",
"icon": "terminal-powershell"
}
},
"html.completion.attributeDefaultValue": "empty",
}
My eslintrc.js looks like this:
module.exports = {
extends: ['../../.eslintrc', 'next', 'plugin:cypress/recommended'],
parserOptions: {
warnOnUnsupportedTypeScriptVersion: false,
},
overrides: [
{
files: ['./cypress/**/*/*.{tsx,ts,js,jsx}'],
rules: {
'import/no-extraneous-dependencies': [
'error',
{ devDependencies: true },
],
},
},
],
};
In Preferences/Settings I have:
Javascript Preferences: Quote Style to "auto"
Typescript preferences: Quote Style to "auto"
I tried setting Editor: Auto Closing Quotes to never
My coworker can copy and paste values from REST responses all day and he does not have to manually edit anything. What in his settings is different?

It sounds like VS Code thinks you are editing JSON. You can manually set the type of file using the menu:
See how in the bottom right mine says Plain Text? Yours likely says JSON. Click that to open the menu you see at the top and then search for Javascript. That should fix it.

Related

Visual studio Code autoimport doesn't work

I am using VSCode autoimport on daily basis with this extension
soates autoimport.
https://github.com/soates/Auto-Import/issues/104.
It suddenly stopped to work. I have tried reinstall vscode, changing extension version, disabling plugins, clearing cache ...etc
I have tried this https://www.youtube.com/watch?v=1yu5tB4KOis and also tried add
checkjs: true to my jsconfig.json. Its very hard to live without auto import.
these are my settings.json
{
"dart.flutterSdkPath": "C:\\Users\\rolni\\AppData\\Roaming\\flutter_windows_v1.12.13+hotfix.9-stable\\flutter\\bin",
"explorer.confirmDelete": false,
"workbench.colorCustomizations": {
"[Material Theme Darker]": {
"statusBar.debuggingBackground": "#212121"
}
},
"material-icon-theme.folders.associations": {
"global_state": "global",
"ui": "layout",
"bloc": "controller"
},
"workbench.iconTheme": "material-icon-theme",
"debug.node.autoAttach": "on",
"[json]": {
"editor.quickSuggestions": {
"strings": true
},
"editor.suggest.insertMode": "replace",
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"typescript.updateImportsOnFileMove.enabled": "always",
"notebook.kernelProviderAssociations": [],
"emmet.triggerExpansionOnTab": true,
"emmet.showSuggestionsAsSnippets": true,
"editor.snippetSuggestions": "top",
"explorer.confirmDragAndDrop": false,
"javascript.updateImportsOnFileMove.enabled": "always",
"highlight-matching-tag.customEmptyElements": null,
"emmet.excludeLanguages": [
"markdown"
],
"emmet.includeLanguages": {
"javascript": "html"
},
"autoimport.filesToScan": "**/*.{ts,tsx,js,jsx}",
"autoimport.showNotifications": true,
"extensions.ignoreRecommendations": true,
"workbench.editor.enablePreview": false,
"outline.showVariables": false,
"debug.javascript.autoAttachFilter": "disabled",
"debug.javascript.terminalOptions": {
"trace": true
},
"[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[jsonc]": {
"editor.defaultFormatter": "vscode.json-language-features"
},
"terminal.integrated.shell.windows": "C:\\Program Files\\PowerShell\\7-preview\\pwsh.exe",
"debug.onTaskErrors": "debugAnyway",
"[go]": {
"editor.insertSpaces": false
},
"go.formatTool": "gofmt",
"go.useLanguageServer": true,
"gopls": {
"usePlaceholders": true, // add parameter placeholders when completing a function
},
"todo-tree.tree.showScanModeButton": false,
"todo-tree.highlights.customHighlight": {
"TODO": {
"icon": "check",
"type": "line",
"iconColour": "yellow",
"foreground": "red",
"background": "yellow"
},
"FIXME": {
"icon": "beaker",
"iconColour": "red",
"foreground": "white",
"background": "red"
}
},
"debug.inlineValues": true,
"editor.codeActionsOnSave": {
"source.organizeImports": true
},
"[typescriptreact]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"tabnine.experimentalAutoImports": true,
"gitlens.hovers.currentLine.over": "line",
"terminal.integrated.tabs.enabled": true,
"go.toolsManagement.autoUpdate": true,
"workbench.colorTheme": "Material Theme",
"git.enableSmartCommit": true,
"todo-tree.general.tags": [
"BUG",
"HACK",
"FIXME",
"TODO",
"XXX",
"[ ]",
"[x]"
],
"todo-tree.regex.regex": "(//|#|<!--|;|/\\*|^|^\\s*(-|\\d+.))\\s*($TAGS)",
"terminal.integrated.defaultProfile.windows": "PowerShell",
"editor.formatOnSave": true,
}
Can't also debug extension all my breakpoints are unbound...can't figure out how to debug it to find root cause of problem.
This log is in my output Log (Extension Host)
[error] [vscode.json-language-features] provider FAILED
[2021-07-05 13:23:44.550] [exthost] [error] Canceled: Canceled
at b.makeCancelError (c:\Users\rolni\AppData\Local\Programs\Microsoft VS Code\resources\app\extensions\json-language-features\client\dist\node\jsonClientMain.js:1:64563)
at b.handleFailedRequest (c:\Users\rolni\AppData\Local\Programs\Microsoft VS Code\resources\app\extensions\json-language-features\client\dist\node\jsonClientMain.js:1:64414)
at c:\Users\rolni\AppData\Local\Programs\Microsoft VS Code\resources\app\extensions\json-language-features\client\dist\node\jsonClientMain.js:1:24756
EDIT:
I have tried remove plugins, directories, settings, but still
autoimport extension is not enabled even it says yes. Its even missing
the log in extension host output.
For JavaScript projects
VSCode in general starts to fail after a while, it OFTEN doesn't suggest imports from package dependencies and even starts to stop hinting auto import for local project src folder files...
As soon as you open the file it will all of a sudden become available...
It's not a plugin issue, it's just VS code, it's starting to get bloated...
For TypeScript projects
It's not so bad, they seem mainly focused on TS these days, but when it goes wrong it goes wrong. I've started un-installing, go to install folders make sure nothing is there and re-install and it works again. No login sync.
Alternative (which I am not a fan off but just works... grrr)
PHPStorm / WebStorm, it gets the import right every time.
And ctrl click on sub methods of class's will auto open that file and locate you on that method. VSCode will just open that file, if it can find it...
With auto complete (in JS Projects) on variables assigned to a class. I think VS Code will only do that if the file is open in the editor.
I keep both open now, VSCode for speed of editing but when (not if) VSCode start to play up, I switch over. Also for the stacking of file tabs feature in PHPStorm instead of a scroll bar of tabs. I find it easier to just switch over to PHPStorm and back again instead of that scroll thing.

How to update users settings.json in vscode with extension packs?

I've developed a vscode extension VSCodeWebDeveloperExperiencePack, Now I'm facing the conflicting between some of them, like turbo console and deploy, I wrote a manual for the configuration on the extension page, as you can see in below:
Pre-defined settings which you maybe want to use:
press ctrl+shift+p
type settings
click on Prefrences: Open settings (JSON) to open your settings.json file
add these lines of settings:
"workbench.iconTheme": "material-icon-theme",
"workbench.colorTheme": "Atom One Dark",
"files.autoSave": "afterDelay",
"editor.fontFamily": "Fira Code",
"editor.fontLigatures": "",
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.fontSize": 16,
"window.zoomLevel": 1,
"sync.gist": "70a5fe700fe4e46aebdf678a5c1db398",
"typescript.preferences.importModuleSpecifier": "non-relative",
"local-history.exclude": [
"**/.history/**",
"**/.vscode/**",
"**/node_modules/**",
"**/typings/**",
"**/out/**",
"**/Code/User/**"
]
Also, there are some keybindings configs like below:
[
{
"key": "ctrl+shift+alt+l",
"command": "bookmarks.jumpToNext",
"when": "editorTextFocus"
},
{
"key": "ctrl+alt+l",
"command": "-bookmarks.jumpToNext",
"when": "editorTextFocus"
},
{
"key": "ctrl+shift+alt+k",
"command": "extension.deploy.listen"
},
{
"key": "ctrl+alt+l",
"command": "-extension.deploy.listen"
}
]
But I want to make it possible or show the user a choice to select configure automatically, which on click on it, or on installing the extension, it put the desiered config to user's settings.json.
I read VScode , but couldn't fix the problem, for example I did add this to my ext-pack package.json:
"contributes": {
"configuration": {
"title": "VsCode Web Developer Experience",
"properties": {
"editor.fontSize": {
"type": "number",
"default": 22,
"description": "this will changes the font settings"
}
}
}
}
I've solved this problem based on vscode docs, here is an example which you can use:
Put this in package.json zpack-package.json:
"contributes": {
"commands": [
{
"command": "zpack.updateConfig",
"title": "Update Essentials Web Extension Pack (ZPack series) Config"
}
]
},
Use this for triggering the action zpack-extension.ts:
import * as vscode from "vscode";
import { extractAsKeyValue, GeneralObject } from "./util";
import { defaultSettings } from "./defaultSettings";
const updateUserSettings = async (settings: GeneralObject[]) => {
settings.forEach(async setting => {
const { key, value } = extractAsKeyValue(setting);
await vscode.workspace
.getConfiguration()
.update(key, value, vscode.ConfigurationTarget.Global);
});
};
export async function activate(context: vscode.ExtensionContext) {
console.log(
'Congratulations, your extension "Essentials Web Extension Pack (ZPack series)" is now active!'
);
let disposable = vscode.commands.registerCommand(
"zpack.updateConfig",
async () => {
console.log(JSON.stringify(defaultSettings, null, 1));
await updateUserSettings(defaultSettings);
await vscode.window.showInformationMessage(
"ZPack Config has been updated"
);
}
);
context.subscriptions.push(disposable);
}
export function deactivate() {}

VScode: Expected Comma Jsonc

When I setting my VScode settings.json. Here I found a bug, the VScode told me"VScode: Expected Comma Jsonc" Why?
**"python.autoComplete.addBrackets": true,
"python.autoComplete.extraPath": ["C:/python/Lib/site-packages"]**
The whole code as follow:
{
"leetcode.defaultLanguage": "python3",
"leetcode.endpoint": "leetcode-cn",
"leetcode.workspaceFolder": "d:\\leetcode-exercise",
"[python]": {
"editor.defaultFormatter": "ms-python.python"
},
"python.autoComplete.extraPaths": [
**"python.autoComplete.addBrackets": true,
"python.autoComplete.extraPath": ["C:/python/Lib/site-packages"]**
]
}
maybe the '{}' is missing?The OK code as follow:
{
"leetcode.defaultLanguage": "python3",
"leetcode.endpoint": "leetcode-cn",
"leetcode.workspaceFolder": "d:\\leetcode-exercise",
"[python]": {
"editor.defaultFormatter": "ms-python.python"
},
"python.autoComplete.extraPaths": [
{ "python.autoComplete.addBrackets": true,
"python.autoComplete.extraPath": ["C:/python/Lib/site-packages"]
}
]
}
By the way,does the '**' has any special function?I didn't retrieve its meaning.Can you tell me? Thanks!

ESLint rule conflicts with Prettier rule

I am totally new to VSCode and this is my first setting. I know that this is a very common problem but I couldn't find a suitable solution for it.
This is my understanding so far. Please correct me if I am wrong.
I want to use ESLint for finding errors in Javascript code and Prettier for formatting all languges. But it seems that we could also format our javascript code with ESLint! There are some useful rules that I like to use it and it seems Prettier don't have those like ( space-in-parens ).
So I decided to use ESLint as my formatter in Javascript. Now I can see that there are a lot of tutorial for "How to integrates ESLint with Prettier" in web. The idea is to extend Prettier rules with a plugin and add those ESLint specific rules to it. Reasonable!
I ended up with the following settings. Please take a look at my settings for using ESLint and Prettier below:
my eslint config file:
module.exports = {
env: {
browser: true,
es6: true,
},
extends: ["prettier"],
globals: {
Atomics: "readonly",
SharedArrayBuffer: "readonly",
},
parserOptions: {
ecmaVersion: 2018,
sourceType: "module",
},
plugins: [
"prettier"
],
"rules": {
"space-in-parens": ["error", "always"],
"quotes": ["error", "single"],
"prettier/prettier": "error"
}
};
my user setting file:
{
"terminal.integrated.shellArgs.linux": [
"-l"
],
"remote.SSH.remotePlatform": {
"dev-all": "linux"
},
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true,
"eslint.alwaysShowStatus": true,
// turn it off for JS and JSX, we will do this via eslint
"[javascript]": {
"editor.formatOnSave": false
},
// tell the ESLint plugin to run on save
"editor.codeActionsOnSave": {
"source.fixAll": true
},
// Optional BUT IMPORTANT: If you have the prettier extension enabled for other languages like CSS and HTML, turn it off for JS since we are doing it through Eslint already
"prettier.disableLanguages": [
"javascript"
]
}
and finally my package.json file:
{
"name": "web",
"version": "1.0.0",
"description": "",
"main": "",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"eslint": "^6.8.0",
"eslint-config-prettier": "^6.10.1",
"eslint-plugin-prettier": "^3.1.3",
"prettier": "^2.0.4"
}
}
Now the problem is that whenever I save my javascript code, formatting toggles! for example with the first save, I have "single quote" and with the next save I have "double quote". I thinks my understanding of the whole idea is wrong. Could you explain it for me and tell me how to correct it. I am spending so much time to figure it. By the way, I have also installed two extensions in vscode: "ESLint" and "Prettier".
This is potentially because of conflicting rules between ESLint and Prettier plugins. Now you have two options
Either let ESLint know that you want to use Prettier as a formatter.
https://dev.to/s2engineers/how-to-make-eslint-work-with-prettier-avoiding-conflicts-and-problems-57pi
2.You can configure ESlint and Prettier together and resolve the conflicting
rules without any conflicts.
https://blog.theodo.com/2019/08/empower-your-dev-environment-with-eslint-prettier-and-editorconfig-with-no-conflicts/
I have decided to let ESLint do formatting for me in JavaScript and prettier for all other languages. You could find my setting on my git.
To solve conflict
install eslint configuration for prettier
npm install eslint-config-prettier
And include it in the extends option in the file .eslintrc.js
extends: [
...,
"prettier",
],
You can follow these settings by Sumit Saha. Your conflicting will be gone. These settings give more power to eslint over prettier. I am copy-pasting those.
In the .vscode/settings.json file :
{
// config related to code formatting
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true,
"[javascript]": {
"editor.formatOnSave": false,
"editor.defaultFormatter": null
},
"[javascriptreact]": {
"editor.formatOnSave": false,
"editor.defaultFormatter": null
},
"javascript.validate.enable": false, //disable all built-in syntax checking
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true,
"source.fixAll.tslint": true,
"source.organizeImports": true
},
"eslint.alwaysShowStatus": true,
// emmet
"emmet.triggerExpansionOnTab": true,
"emmet.includeLanguages": {
"javascript": "javascriptreact"
}
}
And, in the .eslintrc file:
{
"extends": [
"airbnb",
"airbnb/hooks",
"eslint:recommended",
"prettier",
"plugin:jsx-a11y/recommended"
],
"parser": "babel-eslint",
"parserOptions": {
"ecmaVersion": 8
},
"env": {
"browser": true,
"node": true,
"es6": true,
"jest": true
},
"rules": {
"react/react-in-jsx-scope": 0,
"react-hooks/rules-of-hooks": "error",
"no-console": 0,
"react/state-in-constructor": 0,
"indent": 0,
"linebreak-style": 0,
"react/prop-types": 0,
"jsx-a11y/click-events-have-key-events": 0,
"react/jsx-filename-extension": [
1,
{
"extensions": [".js", ".jsx"]
}
],
"prettier/prettier": [
"error",
{
"trailingComma": "es5",
"singleQuote": true,
"printWidth": 100,
"tabWidth": 4,
"semi": true,
"endOfLine": "auto"
}
]
},
"plugins": ["prettier", "react", "react-hooks"]
}
Well, I am happy with TSLint along with ESLint.
And I have a habit of doing Ctrl+Shift+F often during writing code.
Also, you can try indent-rainbow, bracket pair colorizer and my favourite, peacock.

VS Code project code formatting using ESLint

I'm using VS Code for a React project and have VS Code configured to format on save and to Require a 'prettierconfig' to format (the Prettier: Require Config setting from the VSCode Prettier extension). I also have the ESLint plugin enabled.
That seems to mean my project's .prettierrc config file drives the formatting on save and .eslintrc.json provides linting warnings. But in at least one case (below) some formatting issues are left unresolved on save.
The code below, as formatted, shows eslint(indent) squiggly warnings in VS Code. Upon save (Ctrl + S), some get resolved, but some do not.
Specifically, the incorrect indent spacing of the first <div> gets fixed on save and that eslint(indent) warning disappears. However, the later eslint(indent) warnings do NOT get resolved on save. But they DO, however, get resolved when (on Windows) I click Ctrl +Shift+ P, then find and click the "ESLint: Fix all auto-fixable Problems".
When I save the file again those changes are reverted and the warning appears again.
So "format on save" applies different formatting than "ESLint: Fix all auto-fixable Problems". Is there a way to reconcile these? I would like all the eslint(indent) issues to resolve on save.
Does anyone know what ESLint settings drive "ESLint: Fix all auto-fixable Problems"?
const MyModule = () => {
...
return (
// "eslint(indent)" warning on next line gets resolved on save
<div>
{!menus.find(function(permission) {
return permission.level === 'ADMIN';
}) ? (
// "eslint(indent)" warnings below DO NOT get resolved on save
// ... but they DO get resolved on "ESLint: Fix all auto-fixable problems"
// ... then they reappear on save
<div>
<Redirect to="/" />
</div>
) : (
<div>
<Results />
</div>
)}
</div>
);
};
export default MyModule;
My .eslintrc.json contents:
{
"extends": [
"eslint:recommended",
"plugin:import/errors",
"plugin:react/recommended",
"plugin:jsx-a11y/recommended",
"prettier",
"prettier/react"
],
"rules": {
"react/prop-types": 0,
"no-console": 1,
"no-control-regex": 0,
"indent": ["warn", 2],
"quotes": ["warn", "single"],
"space-in-parens": 1,
"prefer-destructuring": 0,
"prefer-const": 0
},
"parser": "babel-eslint",
"plugins": ["react", "import", "jsx-a11y"],
"parserOptions": {
"ecmaVersion": 2018,
"sourceType": "module",
"ecmaFeatures": {
"jsx": true
}
},
"env": {
"es6": true,
"browser": true,
"node": true
},
"settings": {
"react": {
"version": "detect"
}
}
}
My .prettierrc:
{
"useTabs": false,
"printWidth": 120,
"tabWidth": 2,
"singleQuote": true
}
Like the other posted suggested, I use a setup where eslint runs prettier for me. I already had prettier disabled for my js/ts files so I knew that wasn't the issue. It turns out it was the built in formatter for vscode and turning off editor.formatOnSave fixed the issue.
My project's settings.json. This disables the formatter only for typescript files. Eslint will still fix your files as long as you have the eslint auto fix settings enabled.
{
"[typescript]": {
"editor.formatOnSave": false
},
"[typescriptreact]": {
"editor.formatOnSave": false
}
}
Rather than turning off formatOnSave, you could instead set the default formatter to eslint:
{
"[typescript]": {
"editor.defaultFormatter": "dbaeumer.vscode-eslint"
},
"[typescriptreact]": {
"editor.defaultFormatter": "dbaeumer.vscode-eslint"
}
}
Here are the rest of my settings just for reference.
My user settings.json
{
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll": true,
"source.fixAll.eslint": true
},
"eslint.validate": [
"javascript",
"javascriptreact",
"typescript",
"typescriptreact"
],
"prettier.disableLanguages": [
"javascript",
"javascriptreact",
"typescript",
"typescriptreact",
"markdown"
]
}
.eslintrc
{
"root": true,
"parser": "#typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 2018,
"sourceType": "module",
"project": "tsconfig.json",
"warnOnUnsupportedTypeScriptVersion": false
},
"plugins": ["#typescript-eslint", "jest", "prettier"],
"extends": [
"plugin:#typescript-eslint/recommended",
"prettier/#typescript-eslint"
],
"rules": {
"prettier/prettier": [
"error",
{
"tabWidth": 2,
"useTabs": false,
"semi": false,
"singleQuote": true,
"trailingComma": "all",
"printWidth": 110
}
]
}
}
Instead of using both prettier and eslint formatters, just use the eslint formatter and add your prettier options inside your eslintrc file. Here's an example
https://prettier.io/docs/en/integrating-with-linters.html
// .eslintrc.json
...
"rules": {
"prettier/prettier": [
1,
{
"useTabs": false,
"printWidth": 120,
"tabWidth": 2,
"singleQuote": true
}
]
}
...