如何在VSCode中使用Prettier编辑CSS/SCSS/LESS的自动格式化规则?

7gyucuyw  于 2023-03-05  发布在  Vscode
关注(0)|答案(3)|浏览(836)

背景:

我正在使用VSCode的Prettier - Code formatter扩展来自动格式化我的代码。

问题:

我习惯于在sass文件中编写单行块(只有一个属性),即
.some-class { background: #f00; }
问题是Prettier扩展将其格式化为多行,即

.some-class {
    background: #f00;
}

看起来更漂亮的是对css/scss文件使用stylelint,我发现这些设置可以通过在设置中启用它来覆盖:
"prettier.requireConfig": true并使用**. prettierrc. js**文件,但无法关闭单行块的掉毛。如果有人对此有任何修复,将不胜感激。
谢谢

更新:

设置不能被"prettier.requireConfig": true覆盖。VSCode的Prettier - Code formatter扩展没有从VSCode设置编辑样式表的选项。
但是,也可以选择启用stylelint集成,但这需要stylelintstylelint-prettier npm模块
Prettier默认使用standard stylelint configuration进行样式表筛选和格式化。

    • 在下面发布了解决方案。**
r1wp621o

r1wp621o1#

溶液:

为了允许使用Prettier - Code formatter扩展在VSCode中使用单行块,请执行以下步骤:
1.通过在VSCode设置(JSON)中添加以下内容来启用stylelint集成:"prettier.stylelintIntegration": true
1.在项目目录中安装stylelintstylelint-prettiernpm模块。npm install stylelint stylelint-prettier --save-dev
1.使用以下代码在项目目录的根目录下添加**. stylelintrc. json**文件:

{
        "plugins": ["stylelint-prettier"],
        "rules": {
            "block-closing-brace-newline-after": "always-multi-line",
            "block-closing-brace-empty-line-before": "never",
            "block-closing-brace-space-before": "always",
            "block-opening-brace-space-after": "always",
            "block-opening-brace-space-before": "always",
            "block-closing-brace-newline-before": "always-multi-line",
            "block-opening-brace-newline-after": "always-multi-line",
            "indentation": 4
        }
    }

您可以添加/自定义更多的stylelint规则,请参见entire list of rules here
我花了一段时间来理解如何配置这些选项,如果你开始使用stylelint,我强烈推荐你使用read its guidelines first

vwkv1x7d

vwkv1x7d2#

如何配置Visual Studio代码以格式化css/scss/less文件:
1.安装Prettier延伸导线
1.在visual studio中打开css/scss/less文件
1.按键盘上的ctrl + p

  1. VS将要求您配置一个工具来缩进这些文件
    1.从列表中选择更漂亮
xxslljrj

xxslljrj3#

我还不知道vscode有这个特性。一个简单的解决方案可能是指定prettier-ignore

/* prettier-ignore */
.some-class { background: #f00; }

参考:

  • https://prettier.io/docs/en/ignore.html#css

相关问题