【发布时间】:2017-04-30 06:18:30
【问题描述】:
在 VS Code 中编辑函数时,有没有办法禁止删除括号前的空格?
假设我有一个函数
function render () {
// some code here
}
当我开始编辑它时,VS Code 会删除括号前的空格并将此代码转换为:
function render() {
// some code here
}
有没有办法禁用这种行为?
【问题讨论】:
在 VS Code 中编辑函数时,有没有办法禁止删除括号前的空格?
假设我有一个函数
function render () {
// some code here
}
当我开始编辑它时,VS Code 会删除括号前的空格并将此代码转换为:
function render() {
// some code here
}
有没有办法禁用这种行为?
【问题讨论】:
"javascript.format.insertSpaceBeforeFunctionParenthesis": true
function render () {
// some code here
}
"javascript.format.insertSpaceBeforeFunctionParenthesis": false
function render() {
// some code here
}
"editor.formatOnType": true
【讨论】:
"typescript.format.insertSpaceBeforeFunctionParenthesis": true
我在使用匿名函数时遇到了相反的问题。我们使用更漂亮的扩展。自动更正会在括号前插入一个空格。然后更漂亮地抱怨它。
var anonfunc = function() {
// Expected syntax.
}
var autocorrected = function () {
// Auto-correct inserts a space
}
有类似的代码选项,解决了我的问题:
"javascript.format.insertSpaceAfterFunctionKeywordForAnonymousFunctions": false
默认为true。花了我一些时间,直到我厌倦了自动更正。
【讨论】:
"typescript.format.insertSpaceAfterFunctionKeywordForAnonymousFunctions": false
normal 和anonymous 函数有不同的设置。看起来像 normal 函数,默认是 false,但对于 anonymous,我必须在 settings.json 中明确设置。
我是 VSCode 团队的一员。从 VSCode 1.8 开始,此格式选项不支持开箱即用,但我们正在跟踪该功能:https://github.com/Microsoft/vscode/issues/15386、https://github.com/Microsoft/TypeScript/issues/12234
作为一种解决方法,请尝试以下方法:
ext install eslint
"eslint.autoFixOnSave": true 添加到您的工作区或用户设置中在项目的根目录中,创建一个 .eslintrc.json 并使用:
{
...
"rules": {
...
"space-before-function-paren": "error"
}
}
eslint 扩展可以使用create .eslintrc.json 命令为你创建一个starter .eslintrc.json。
这将在您保存文件时自动格式化函数,使其后有一个空格。
【讨论】:
就我而言,我想要 VS Code 的正常缩进/格式化行为,所以我禁用了 eslint 警告:
在 .eslintrc.js 文件中,我在规则中键入:
'rules': {
....
//disable rule of space before function parentheses
"space-before-function-paren": 0
}
【讨论】:
package.json 中。
我发现我启用了"editor.formatOnType": true 设置。这就是使编辑器在您键入时自动格式化代码的原因。禁用它有助于解决问题。
【讨论】:
"editor.formatOnSave": true 设置。 (我在保存文件时遇到了问题)。
另外添加到 Yan 的答案,您可以在 Mac 上点击 Command + , 或在键盘上点击 CTRL + , 然后,在您的 settings.json 中添加以下行
"javascript.format.insertSpaceBeforeFunctionParenthesis": false,
"javascript.format.insertSpaceAfterFunctionKeywordForAnonymousFunctions": false
第二个条目还禁用匿名函数的空间,例如格式
var anon = function() {
// do something..
}
【讨论】:
在我的情况下,我必须在我的 Vue.js 项目上显式启用 ESLint,即使我有一个应该已经实现的 .eslintrc.js 文件:
extends: ['plugin:vue/exxential', '@vue/standard']
为此,我按下 CTRL+Shift+P 并搜索“ESLint: Enable ESLint”
【讨论】:
我的问题在package.json
我的项目使用prettier@1.18.2,它没有space after the function keyword 或arrowParens: 'always' 作为默认配置。
其中一位维护者将 prettier 升级到了版本 2 prettier@2.3.2,其中将这两个作为默认配置。这些是更漂亮的版本 2 中的重大变化。
https://prettier.io/blog/2020/03/21/2.0.0.html#always-add-a-space-after-the-function-keyword-3903
https://prettier.io/blog/2020/03/21/2.0.0.html#change-default-value-for-arrowparens-to-always-7430
npm ci - 刚刚重新安装了 npm 包。
npm install 也可以。 npm ci 将安装来自 package-lock.json 的确切版本,而 npm install 将安装最新版本并进行细微更改。
【讨论】: