如何一键格式化你的样式代码(不仅仅是书写格式,书写顺序也一并格式化了)

139 阅读1分钟

当下代码格式化工具非常多,最常用的就是 prettier+eslint 的组合,但是经常面临不能足够优秀的格式化样式代码,往往只能格式化书写格式,但是不能格式化书写顺序

css 样式的书写顺序其实是建议有一定规范的 属性书写顺序 | css 编码规范 (itmyhome.com)

image.png

熟练按照这个规范写样式才能让你的代码看起来更舒服、更清晰。 但是不少人更习惯于随意的书写样式(是萌新的我没错了!)以及同层级的先后顺序也不太好统一(比如 width 和 margin 到底谁先谁后),这样依赖,就不便于团队管理代码风格了。

所以为了解决上述痛点,就需要有一个能一键格式化书写顺序的插件了。

话不多说,直接上配置 在你的项目根目录下安装这些插件

image.png

 "prettier": "^2.3.2",
    "prettier-plugin-packagejson": "^2.2.18",
    "prettier-plugin-two-style-order": "^1.0.0",
    "stylelint": "^13.0.0",
    "stylelint-config-css-modules": "^2.2.0",
    "stylelint-config-prettier": "^8.0.1",
    "stylelint-config-standard": "^20.0.0",
    "stylelint-declaration-block-no-ignored-properties": "^2.1.0",

(方便复制粘贴)

然后新建 stylelint.js

/** @format */
module.exports = {
  extends: [
    'stylelint-config-standard',
    'stylelint-config-css-modules',
    'stylelint-config-prettier',
  ],
  plugins: ['stylelint-declaration-block-no-ignored-properties'],
  rules: {
    'no-descending-specificity': null,
    'function-url-quotes': 'always',
    'selector-attribute-quotes': 'always',
    'font-family-no-missing-generic-family-keyword': null,
    'plugin/declaration-block-no-ignored-properties': true,
    'unit-no-unknown': [true, { ignoreUnits: ['rpx'] }],
    // webcomponent
    'selector-type-no-unknown': null,
    'value-keyword-case': ['lower', { ignoreProperties: ['composes'] }],
  },
  ignoreFiles: ['**/*.js', '**/*.jsx', '**/*.tsx', '**/*.ts'],
};

接下来你就可以在你的样式文件里一键格式化代码拉!

image.png

image.png

只能说是肥肠好用~