函数括号前的代码空间

在 VS 代码中编辑函数时,是否有方法禁用删除括号前的空格?

假设我有一个函数

function render () {
// some code here
}

当我开始编辑它时,VS Code 删除括号前的空格并将这段代码转换为:

function render() {
// some code here
}

有办法解除这种行为吗?

75646 次浏览

我是 VSCode 团队的。从 VSCode 1.8开始,这个格式化选项就不受支持了,但是我们正在跟踪这个特性: https://github.com/Microsoft/vscode/issues/15386https://github.com/Microsoft/TypeScript/issues/12234

作为一种变通方法,尝试以下方法:

  • 安装 弹簧夹紧延伸: ext install eslint
  • "eslint.autoFixOnSave": true添加到工作区或用户设置中
  • 在项目的根目录中,创建一个 .eslintrc.json,其中包含:

    {
    ...
    "rules": {
    ...
    "space-before-function-paren": "error"
    }
    }
    

    Eslint 扩展可以使用 create .eslintrc.json命令为您创建启动器 .eslintrc.json

这将自动格式化函数,以便在保存文件时在它们之后有一个空格。

我发现我启用了 "editor.formatOnType": true设置。这使得编辑器在您键入代码时自动格式化代码。禁用它有助于解决问题。

在我的例子中,我需要 VS Code 的正常缩进/格式化行为,所以我禁用了 eslint 警告:

在. eslintrc.js 文件中,我在规则中键入:

 'rules': {
....


//disable rule of space before function parentheses
"space-before-function-paren": 0
}
  1. 在 VS 代码中打开文件-> 首选项-> 设置
  2. 添加到您的 JSON 配置:

"javascript.format.insertSpaceBeforeFunctionParenthesis": true

function render () {
// some code here
}

"javascript.format.insertSpaceBeforeFunctionParenthesis": false

function render() {
// some code here
}

  1. 现在您可以继续使用自动格式选项 "editor.formatOnType": true

我在匿名函数方面遇到了相反的问题。我们用更漂亮的外延。自动更正在括号前插入空格。然后更漂亮的人会抱怨。

var anonfunc = function() {
// Expected syntax.
}


var autocorrected = function () {
// Auto-correct inserts a space
}

还有一个类似的代码选项,可以解决我的问题:

"javascript.format.insertSpaceAfterFunctionKeywordForAnonymousFunctions": false

默认是 true。花了我一些时间,直到我厌倦了纠正自动更正。

在我的例子中,我必须在 Vue.js 项目上显式地启用 ESLint,即使我有一个。Js 文件,该文件应该实现:

extends: ['plugin:vue/exxential', '@vue/standard']

要做到这一点,我按下 CTRL + S hift + P 并搜索“ ESLint: Enable ESLint”

转到首选项,在顶部的搜索栏中搜索 insertSpaceBeforeFunctionParenthesis

现在,选中显示 JavaScript: Format: Insert Space Before Function Parenthesis的复选框

enter image description here

我也遇到过类似的问题,VSCode 在构造函数和 ESLint 之后删除空格,因为没有空格。

  • 转到文件-> 首选项-> 设置
  • 搜索 constructor
  • JavaScript › Format: Insert Space After Constructor旁边添加支票

enter image description here

同时,你也可以在 Mac 上点击 Command + ,,或者在键盘上点击 CTRL + ,,然后在你的 settings.json中添加以下几行

"javascript.format.insertSpaceBeforeFunctionParenthesis": false,
"javascript.format.insertSpaceAfterFunctionKeywordForAnonymousFunctions": false

第二个条目还禁用了匿名函数的空间,例如格式为

var anon = function() {
// do something..
}

问题:

我的问题是在 package.json

我的项目是使用 prettier@1.18.2,它没有 space after the function keywordarrowParens: 'always'作为默认配置。

其中一个维护人员将更漂亮的版本升级到了版本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将安装最新版本,只做一些小的更改。