如何避免script标签中的多属性被prettier的singleAttributePerLine格式化?

问题描述

开发了一个vue3项目,在script标签中使用了setup语法糖,同时又是一个ts项目,指明了lang属性,所以这个script成了多属性,恰巧prettier配置了singleAttributePerLine(最初目的是想对vue组件的多属性进行换行),保存格式化之后script中的属性意外换行了,但这并不是我想要的,我仅仅想对组件的多属性进行换行,便于阅读代码

prettier配置singleAttributePerLine为false时

{
  "singleAttributePerLine": false
}

.vue文件的script标签格式化后是这样子

<script setup lang="ts">
// ...
</script>

prettier配置singleAttributePerLine为true时,.vue文件的script标签格式化后是这样子

<script
  setup
  lang="ts"
>
// ...
</script>

相关代码

.prettierrc

{
  "printWidth": 70,
  "tabWidth": 2,
  "useTabs": false,
  "semi": false,
  "singleQuote": true,
  "quoteProps": "as-needed",
  "jsxSingleQuote": false,
  "trailingComma": "none",
  "bracketSpacing": true,
  "bracketSameLine": false,
  "arrowParens": "always",
  "endOfLine": "auto",
  "singleAttributePerLine": true
}

.eslintrc.js

module.exports = {
  root: true,
  env: {
    node: true
  },
  extends: [
    'eslint:recommended',
    'plugin:vue/vue3-recommended',
    'plugin:@typescript-eslint/recommended',
    'prettier'
  ],
  plugins: ['@typescript-eslint'],
  parser: 'vue-eslint-parser',
  parserOptions: {
    parser: '@typescript-eslint/parser',
    ecmaVersion: 'latest',
    sourceType: 'module',
    jsxPragma: 'React',
    ecmaFeatures: {
      jsx: true
    }
  },
  rules: {
    'no-undef': 'off',
    // 数组函数需要有返回值
    'array-callback-return': 'error',
    // 函数复杂度不能超过20
    complexity: ['error', { max: 20 }],
    // 使用 === 而不是 ==
    eqeqeq: ['error', 'smart'],
    // 多个运算符需要用()分隔
    // 'no-mixed-operators': 'error',
    // 当存在更简单的替代方案时,不允许使用三元运算符
    'no-unneeded-ternary': 'error',
    // 强制块语句的最大可嵌套深度
    'max-depth': ['error', 4],
    // 限制函数定义中最大参数个数
    'max-params': ['error', 3],
    // 强制回调函数最大嵌套深度
    'max-nested-callbacks': [1, 3],
    // 强制文件的最大行数
    'max-lines': ['error', 500],
    // 建议使用const
    'prefer-const': [
      'error',
      {
        // 在解构中,所有变量都应该是const
        destructuring: 'all'
      }
    ],
    // 使用点号
    'dot-notation': 'error',
    // 适配eslint 未使用的变量
    '@typescript-eslint/no-unused-vars': 'error',
    // 允许非空断言
    '@typescript-eslint/no-non-null-assertion': 'off',
    // 允许自定义模块和命名空间
    '@typescript-eslint/no-namespace': 'off',
    // 允许对this设置alias
    '@typescript-eslint/no-this-alias': 'off',
    // 允许使用any类型
    '@typescript-eslint/no-explicit-any': ['off'],
    // 强制标签自闭合
    'vue/html-self-closing': [
      'warn',
      {
        html: {
          void: 'always',
          normal: 'never',
          component: 'always'
        },
        svg: 'always',
        math: 'always'
      }
    ]
  }
}

你期待的结果是什么?实际看到的错误信息又是什么?

如何避免script标签中的多属性被prettier的singleAttributePerLine格式化

阅读 5.8k
1 个回答

已经解决,升级prettier到2.7以上就好了,这个月初有人提了一个merge

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题