首页 > 解决方案 > Visual Studio Code 和 TSLint:代码换行到 80 多个字符

问题描述

我在 Visual Studio Code 中使用带有 TSLint 和 Prettier 的 TypeScript 来编写 React Native App。

我尝试将我的编辑器配置为每行自动将代码包装为 100 个字符。但保存后总是 80 个字符,而不是 100 个。

以下是我更改的设置:

"prettier.tslintIntegration": true,
"prettier.printWidth": 100,
"editor.renderIndentGuides": true,
"editor.rulers": [100],
"editor.wordWrapColumn": 100,
"editor.formatOnSave": true

这是我的tslint.json

{
  "extends": ["tslint:recommended", "tslint-react", "tslint-config-prettier"],
  "rules": {
    // "jsx-no-lambda": false,
    "member-access": false,
    "interface-name": false,
    "max-line-length": [true, 100]
  }
}

即使我以这种方式配置了所有内容,我的代码仍然会自动换行大约 80 个字符。我怎样才能让它停止?

如果我的行超过 100 个字符,我会收到一个 linting 错误,因此该tslint.json设置似乎有效。

奖励:完成 VSCode 设置以防我错过了什么:

{
  "telemetry.enableTelemetry": false,
  "workbench.colorTheme": "One Dark Pro",
  "workbench.iconTheme": "vscode-icons",
  "window.zoomLevel": 0,
  "prettier.eslintIntegration": true,
  "prettier.tslintIntegration": true,
  "prettier.printWidth": 100,
  "editor.renderIndentGuides": true,
  "editor.rulers": [100],
  "[javascript]": {
    "editor.tabSize": 2
  },
  "[typescript]": {
    "editor.tabSize": 2
  },
  "[typescriptreact]": {
    "editor.tabSize": 2
  },
  "[json]": {
    "editor.tabSize": 2
  },
  "workbench.colorCustomizations": {
    // "statusBar.background": "#272b33",
    // "panel.background": "#30353f",
    // "sideBar.background": "#2a2b33",
    "editor.background": "#2c313a"
  },
  "todohighlight.keywords": [
    {
      "text": "DEBUG:",
      "color": "#fff",
      "backgroundColor": "limegreen",
      "overviewRulerColor": "grey"
    },
    {
      "text": "NOTE:",
      "color": "#fff",
      "backgroundColor": "mediumslateblue",
      "overviewRulerColor": "grey"
    },
    {
      "text": "REVIEW:",
      "color": "#fff",
      "backgroundColor": "dodgerblue",
      "overviewRulerColor": "grey"
    },
    {
      "text": "XXX:",
      "color": "#fff",
      "backgroundColor": "orangered",
      "overviewRulerColor": "grey"
    }
  ],
  "editor.wordWrapColumn": 100,
  "editor.formatOnSave": true
}

标签: typescriptvisual-studio-codeword-wraptslintprettier

解决方案


这两个应该足够了:

"editor.wordWrap": "wordWrapColumn",
"editor.wordWrapColumn": 100

您的设置中似乎"editor.wordWrap"缺少。在 vscode 中,此设置控制换行策略:“wordWrapColumn”表示"editor.wordWrapColumn"设置时换行。

您也可以尝试"editor.wordWrap": "bounded"哪个会尊重“wordWrapColumn”,但如果您的视口小于您定义的列数,也可以换行。

UPD:根据我们在评论中的讨论,prettier 似乎不尊重它的"printWidth"设置。可能有两个最可能的原因:

  1. 本期:https ://github.com/prettier/prettier-vscode/issues/595
  2. 定义配置选项的优先级:https ://github.com/prettier/prettier-vscode#prettiers-settings 。特别是,它首先搜索更漂亮的配置文件,而不是.editorconfig文件,然后才搜索 vscode 设置。

作为一种解决方法,您可以尝试在项目的更漂亮的配置文件中或在 editorconfig 文件中实际定义此设置,并检查 vscode 插件是否适用于其中任何一个。


推荐阅读