跳至主要內容

代码规范

wangdx大约 17 分钟

{
    "husky": "^4.2.5",
    "lint-staged": "^11.0.1",
    "eslint": "^6.8.0",
    "eslint-plugin-html": "^6.1.0",
    "eslint-plugin-vue": "^6.2.2",
    "babel-eslint": "^10.1.0",
    "stylelint": "^13.13.1",
    "stylelint-config-recess-order": "^2.4.0",
    "stylelint-config-standard": "^22,
    "@commitlint/cli": "^12.1.4",
    "@commitlint/config-conventional": "^12.1.4",
}

husky+lint-staged+Commitlint

husky

  • 可以用于实现各种 git Hook。这里主要用到 pre-commit 这个 hook,在执行 commit 之前,运行一些自定义操作

lint-staged

  • 用于对 git 暂存区中的文件执行代码检测

配置 lint-staged 规则 在 package.json 里 添加

"lint-staged": {
    "*.{js,vue}": [
      "prettier --write",
      "eslint --fix",
    ],
    "*.less": [
      "stylelint --fix"
    ]
}
配置 husky 检验钩子
"husky": {
    "hooks": {
      "pre-commit": "lint-staged",
      "commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
    }
}

@commitlint/cli 可以检查提交信息

@commitlint/config-conventional 是提交规范的配置包

npm i husky lint-staged -D
npm i @commitlint/cli @commitlint/config-conventional -D
/*
  规范commit日志
  https://commitlint.js.org
*/

const types = [
    'build', // 主要目的是修改项目构建系统(例如glup,webpack,rollup的配置等)的提交
    'ci', // 修改项目的持续集成流程(Kenkins、Travis等)的提交
    'chore', // 构建过程或辅助工具的变化
    'docs', // 文档提交(documents)
    'feat', // 新增功能(feature)
    'fix', // 修复 bug
    'pref', // 性能、体验相关的提交
    'refactor', // 代码重构
    'revert', // 回滚某个更早的提交
    'style', // 不影响程序逻辑的代码修改、主要是样式方面的优化、修改
    'test', // 测试相关的开发,
  ],
  typeEnum = {
    rules: {
      'type-enum': [2, 'always', types],
    },
    value: () => {
      return types;
    },
  };

module.exports = {
  extends: ['@commitlint/config-conventional'],
  /*
  Level [0..2]: 0 disables the rule. For 1 it will be considered a warning for 2 an error.
  https://commitlint.js.org/#/reference-rules
*/
  rules: {
    'type-enum': typeEnum.rules['type-enum'],
    'subject-full-stop': [0, 'never'],
    'subject-case': [0, 'never'],
  },
};

Eslint 配置

npm i eslint eslint-plugin-html eslint-plugin-vue babel-eslint -D
module.exports = {
  root: true,
  // parser: 'babel-eslint',
  env: {
    node: true,
  },
  // extends: ["plugin:vue/base", "plugin:vue/recommended"],
  extends: ["plugin:vue/base"],
  parserOptions: {
    parser: "babel-eslint",
  },
  plugins: ["html", "vue"],
  rules: {
    /*
    "off"或者0    //关闭规则关闭
    "warn"或者1    //在打开的规则作为警告(不影响退出代码)
    "error"或者2    //把规则作为一个错误(退出代码触发时为1) 
    */

    "no-var": "error", // 禁止使用var
    "prefer-const": "error", // 建议使用const
    "no-const-assign": "error", // 禁止修改使用const(no-const-assign)声明的变量
    "object-shorthand": "error", // 方法属性值简写
    "quote-props": ["error", "as-needed"], // 只对那些无效的标示使用引号 ''
    "no-array-constructor": "error", // 数组要求字面量赋值
    "no-new-object": "error", // 对象使用字面值创建对象
    "array-callback-return": "error", // 在数组方法的回调中强制执行
    "prefer-destructuring": [
      "error",
      {
        array: true,
        object: true,
      },
      {
        enforceForRenamedProperties: false,
      },
    ], // 用对象的解构赋值来获取和使用对象某个或多个属性值
    quotes: ["error", "single"], // string 统一用单引号 ''
    "prefer-template": "error", // 建议使用模板字符串
    "no-eval": "error", // 禁止使用eval
    "no-useless-escape": "error", // 不要使用不必要的转义字符
    "func-style": "error", // 用命名函数表达式而不是函数声明
    "prefer-rest-params": "error", // 建议使用rest参数而不是参数
    "space-before-function-paren": ["error", "never"], // 函数前不允许使用空格或
    "space-before-blocks": ["error", "always"], // 块前需要空格
    "no-param-reassign": "error", // 不允许重新分配函数参数
    "prefer-spread": "error", // 建议使用spread语法而不是.apply()
    "prefer-arrow-callback": "error", // 建议使用箭头函数
    "arrow-spacing": "error", // 箭头函数的箭头前后需要空格
    //  "arrow-parens": ["error", "always"], // 在arrow函数参数中需要paren
    "arrow-body-style": ["error", "always"], // 在箭头函数体中需要大括号
    "no-confusing-arrow": ["error", { allowParens: true }], // 不允许箭头函数与比较混淆
    "no-useless-constructor": "error", // 不允许不必要的构造函数
    "no-dupe-class-members": "error", // 不允许在类成员中使用重复名称
    "no-duplicate-imports": ["error", { includeExports: true }], // 不允许重复导入
    //  "import/no-mutable-exports": "error", // 不要导出可变的绑定
    //  "import/prefer-default-export": "error", // 在只有一个导出的模块里,用 export default 更好
    //  "import/first": "error", // import 放在其他所有语句之前
    "dot-notation": "error", // 访问属性时使用点符号
    "no-restricted-properties": "error", // 做幂运算时用幂操作符 **
    "one-var": ["off", "always"], // 强制在函数中单独声明变量
    "no-multi-assign": "error", // 不要使用连续变量分配
    "no-plusplus": "error", // 不要使用一元递增递减运算符(++, --)
    "no-unused-vars": "off", // 不允许有未使用的变量
    eqeqeq: ["error", "always"], // 使用 === 和 !== 而不是 == 和 !=
    "no-case-declarations": "error", // 不允许在case/default子句中使用词法声明
    "no-nested-ternary": "error", // 三元表达式不应该嵌套,通常是单行表达式
    "no-unneeded-ternary": "error", // 避免不需要的三元表达式
    "no-mixed-operators": "error", // 不允许不同运算符的混合
    "nonblock-statement-body-position": ["error", "beside"], // 强制单行语句的位置
    "brace-style": "error", // 需要大括号样式
    "no-else-return": "error", // 如果if语句都要用return返回,那后面的else就不用写了。如果if块中包含return,它后面的else if块中也包含了return,这个时候就可以把else if拆开
    "spaced-comment": [
      "error",
      "always",
      {
        line: {
          markers: ["/"],
          exceptions: ["-", "+"],
        },
        block: {
          markers: ["!"],
          exceptions: ["*"],
          balanced: true,
        },
      },
    ],
    //  "indent": ["error", 2, { "SwitchCase": 1}], // 强制2个空格
    "keyword-spacing": ["error", { before: true }], // 在关键字前后强制使用一致的间距
    "space-infix-ops": ["error", { int32Hint: false }], // 用空格来隔开运算符
    "padded-blocks": ["error", "never"], // 不要故意留一些没必要的空白行
    "array-bracket-spacing": ["error", "never"], // 方括号里不要加空格
    "object-curly-spacing": ["error", "always"], // 花括号 {} 里加空格
    "comma-spacing": ["error", { before: false, after: true }], //  , 前避免空格, , 后需要空格
    "key-spacing": ["error", { beforeColon: false }], // 在对象的属性中, 键值之间要有空格
    "no-trailing-spaces": "error", // 行末不要空格
    "no-multiple-empty-lines": "error", // 避免出现多个空行。 在文件末尾只允许空一行
    "no-new-wrappers": "error", // 不允许基元包装实例
    radix: ["error", "as-needed"], // 需要基数参数
    //  "id-length": "error",
    camelcase: ["error", { properties: "always" }], // 要求驼峰式命名对象、函数、实例
    "new-cap": "off", // 要求构造函数名称以大写字母开头
    "no-underscore-dangle": "error", // 不要用前置或后置下划线
  },
};

eslint-config-prettier

我们看下 eslint-config-prettier/index.js,这些都是 ESLint 本身已经定义好的规则,eslint-config-prettier/index.js 没有创造新的规则,它只是关闭了 ESLint 中一些不必要的规则以及可能与 Prettier 冲突的规则 。请注意,这个配置只能关闭规则,所以只有和其他配置一起使用才有意义。 从下面这个文件可以看出:被关闭的规则一些是 0,一些是 'off'。0 表示这些规则在某些选项下是不会和 Prettier 规则冲突的。

eslint-config-prettier 下还有 @typescript-eslint.js, babel.js, react.js, prettier.js, vue.js 等文件,其内容是禁掉与它搭配使用的插件中创建的与 Prettier 冲突的规则。

  • 例如:当我们想校验 ts 文件时,需要引入 @typescript-eslint/eslint-plugin,这个插件中存在一些与 Prettier 冲突的规则,prettier/@typescript-eslint.js 就是禁掉这些规则。
1.
pnpm i -D eslint-config-prettier
2.
将 eslint-config-prettier 添加到 .eslintrc.js 文件的 "extends" 数组中。确保把它放在最后,这样它就有机会覆盖其他配置。
module.exports = {
  root: true,
  env: {
    node: true,
  },
  extends: [
    "plugin:vue/essential",
    "eslint:recommended",
    "@vue/typescript/recommended",
    "plugin:prettier/recommended",
    "prettier", // eslint-config-prettier 可简写成 prettier
  ],
  parserOptions: {
    ecmaVersion: 2020,
  },
  rules: {
    "no-console": process.env.NODE_ENV === "production" ? "warn" : "off",
    "no-debugger": process.env.NODE_ENV === "production" ? "warn" : "off",
  },
};

eslint-plugin-prettier

eslint-plugin-prettier 以 ESLint 规则的方式运行 Prettier,通过 Prettier 找出格式化前后的差异,并以 ESLint 问题的方式报告差异,同时针对不同类型的差异提供不同的 ESLint fixer。

  • 注意:eslint-plugin-prettier 不会自动安装 Prettier,你需要自己安装。

Prettier

Prettier 是一个有态度的代码格式化程序,支持:

module.exports = {
  // 一行最多 100 字符
  printWidth: 100,
  // 不使用缩进符,而使用空格
  useTabs: false,
  // 使用 2 个空格缩进
  tabWidth: 2,
  tabSize: 2,
  // 行尾需要有分号
  semi: true,
  // 使用单引号
  singleQuote: true,
  // jsx 不使用单引号,而使用双引号
  jsxSingleQuote: false,
  // 末尾不需要逗号 'es5'  none
  trailingComma: "es5",
  // 大括号内的首尾需要空格
  bracketSpacing: true,
  // jsx 标签的反尖括号需要换行
  jsxBracketSameLine: false,
  // 在单个箭头函数参数周围加上括号<avoid|always>
  arrowParens: "avoid",
  // 不需要写文件开头的 @prettier
  requirePragma: false,
  // 不需要自动在文件开头插入 @prettier
  insertPragma: false,
  // 使用默认的折行标准
  proseWrap: "preserve",
  // 换行符使用 lf 结尾是 \n \r \n\r auto
  endOfLine: "lf",
  vueIndentScriptAndStyle: true,
};

Stylelint

stylelint-config-standard 是 stylelint 的推荐配置 stylelint-order css 属性排序插件(先写定位,再写盒模型,再写内容区样式,最后写 CSS3 相关属性) stylelint-config-recess-order stylelint-order 插件的第三方配置

pnpm i stylelint stylelint-config-html stylelint-config-standard stylelint-config-recommended stylelint-order stylelint-config-recess-order -D
module.exports = {
  processors: [],
  plugins: [],
  extends: ["stylelint-config-standard", "stylelint-config-recess-order"],
  rules: {}, // 可以自己自定一些规则
};

项目搭建详细

使用 Vite/vue Cli 脚手架初始化项目

1.
pnpm create vite development-app --template vue-ts

选择vue-ts模板

修改vite.config.ts,修改域名端口,自动打开浏览器
server: {
    host: 'localhost',
    port: 7070,
    open: true
}
2.
vue create vue2-case

const { defineConfig } = require("@vue/cli-service");
// vue.config.js 配置说明
//官方vue.config.js 参考文档 https://cli.vuejs.org/zh/config/#css-loaderoptions
// 这里只列一部分,具体配置参考文档
module.exports = defineConfig({
  // 部署生产环境和开发环境下的URL。
  // 默认情况下,Vue CLI 会假设你的应用是被部署在一个域名的根路径上
  // 例如 https://www.ruoyi.vip/。如果应用被部署在一个子路径上,你就需要用这个选项指定这个子路径。例如,如果你的应用被部署在 https://www.ruoyi.vip/admin/,则设置 baseUrl 为 /admin/。
  publicPath: process.env.NODE_ENV === "production" ? "/" : "/",
  // 在npm run build 或 yarn build 时 ,生成文件的目录名称(要和baseUrl的生产环境路径一致)(默认dist)
  outputDir: "dist",
  // 用于放置生成的静态资源 (js、css、img、fonts) 的;(项目打包之后,静态资源会放在这个文件夹下)
  assetsDir: "static",
  // 是否开启eslint保存检测,有效值:ture | false | 'error'
  lintOnSave: process.env.NODE_ENV === "development",
  // 如果你不需要生产环境的 source map,可以将其设置为 false 以加速生产环境构建。
  productionSourceMap: process.env.NODE_ENV === "development",
  //开发服务配置
  devServer: {
    port: 3000, //启动端口号
    host: "0.0.0.0",
    open: false, //启动后是否自动打开浏览器
    proxy: {
      // detail: https://cli.vuejs.org/config/#devserver-proxy
      [process.env.VUE_APP_BASE_API]: {
        target: `http://localhost:8080`,
        changeOrigin: true,
        ws: true,
        pathRewrite: {
          ["^" + process.env.VUE_APP_BASE_API]: "",
        },
      },
    },
  },
});


//运行项目
pnpm run serve
//打包项目
pnpm run build
//项目检查
pnpm run lint

代码加入 eslint 校验,与 prettier 自动格式化

  • eslint 运行代码前就可以发现一些语法错误和潜在的 bug,目标是保证团队代码的一致 性和避免错误
  • prettier 是代码格式化工具,用于检测代码中的格式问题,比如单行代码长度,tab 长 度,空格,逗号表达式等等

区别联系:eslint 偏向于把控项目的代码质量,而 prettier 更偏向于统一项目的编码 风格。eslint 有小部分的代码格式化功能,一般和 prettier 结合使用

pnpm install eslint eslint-plugin-vue eslint-config-prettier prettier eslint-plugin-import eslint-plugin-prettier eslint-config-airbnb-base -D

eslint: ESLint的核心库
prettier: prettier格式化代码的核心库
eslint-config-airbnb-base airbnb的代码规范(依赖plugin-import)
eslint-config-prettier  eslint结合prettier的格式化
eslint-plugin-vue   eslint在vue里的代码规范
eslint-plugin-import  项目里面支持eslint
eslint-plugin-prettier  将prettier结合进去eslint的插件
@rushstack/eslint-patch 它可以让我们在不修改 ESLint 配置的情况下,以插件的形式,对 ESLint 进行修改和扩展

配置script脚本,项目安装eslint配置
"lint:create": "eslint --init"

执行npm run lint:create

会自动创建一个.eslintrc.cjs文件

安装完成后,后面的启动项目还缺少一些依赖,提前按需安装好
pnpm install typescript @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint-import-resolver-alias @types/eslint @types/node -D

@typescript-eslint/parser    eslint解析器,解析typescript,检查规范typescript代码
@typescript-eslint/eslint-plugin  eslint插件,包含了各类定义好的检测typescript代码的规范
eslint-import-resolver-alias   让我们可以用import的时候使用@别名

eslintrc 文件的修改

因为 eslint 是 node 工具,所以文件名是.cjs 结尾(commonjs 规范)——对应 的.mjs 就是 ES Module 规范

修改 package.json 文件,添加一个脚本命令 "lint": "eslint "src/*/.{js,vue,ts}" --fix"

module.exports = {
 // 环境:
 env: {
  // 浏览器
  browser: true,
  // 最新es语法
  es2021: true,
  // node环境
  node: true,
 },
 // 扩展的eslint规范语法,可以被继承的规则
 // 字符串数组:每个配置继承它前面的配置
 // 分别是:
 // eslint-plugin-vue提供的
 // eslint-config-airbnb-base提供的
 // eslint-config-prettier提供的
 // 前缀 eslint-config-, 可省略
 extends: [
  'plugin:vue/vue3-strongly-recommended',
  'airbnb-base',
  'prettier'
 ],
 // eslint 会对我们的代码进行检验
 // parser的作用是将我们写的代码转换为ESTree(AST)
 // ESLint会对ESTree进行校验
 parser: 'vue-eslint-parser',
 // 解析器的配置项
 parserOptions: {
  // es的版本号,或者年份都可以
  ecmaVersion: 'latest',
  parser: '@typescript-eslint/parser',
  // 源码类型 默认是script,es模块用module
  sourceType: 'module',
  // 额外的语言类型
  ecmaFeatures: {
   tsx: true,
   jsx: true,
  },
 },
 // 全局自定义的宏,这样在源文件中使用全局变量就不会报错或者警告
 globals: {
  defineProps: 'readonly',
  defineEmits: 'readonly',
  defineExpose: 'readonly',
  withDefault: 'readonly',
 },
 // 插件
 // 前缀 eslint-plugin-, 可省略
 // vue官方提供了一个ESLint插件 eslint-plugin-vue,它提供了parser和rules
 // parser为 vue-eslint-parser,放在上面的parsr字段,rules放在extends字段里,选择合适的规则
 plugins: [
  'vue',
  '@typescript-eslint'
 ],
 settings: {
  // 设置项目内的别名
  'import/reslover': {
   alias: {
    map: [
     ['@', './src']
    ],
   },
  },
  // 允许的扩展名
  'import/extensions': ['.js', '.jsx', '.ts', '.tsx', '.mjs'],
 },
 // 自定义规则,覆盖上面extends继承的第三方库的规则,根据组内成员灵活定义
 rules: {
  'import/no-extraneous-dependencies': 0,
  'no-param-reassing': 0,
  'vue/multi-word-commponent-names': 0,
  'vue/attribute-hyphenation': 0,
  'vue/v-on-event-hyphenation': 0,
 },
};

修改 vite.config.js

pnpm install vite-plugin-eslint -D
vite的一个插件,让项目可以方便的得到eslint支持,完成eslint配置后,可以快速的将其集成进vite之中,便于在代码不符合eslint规范的第一时间看到提示

import eslintPlugin from 'vite-plugin-eslint'

plugins: [vue(), eslintPlugin()]

修改添加常见配置文件

外部新建文件 .eslintrcignore、.prettierrc.cjs、.prettierignore

修改 package.json 文件,添加一个脚本命令 "prettier-format": "prettier --config .prettierrc.cjs "src/*/.{vue,js,ts}" --write"

.eslintrcignore文件内容:

*.sh
node_modules
*.md
*.woff
*.ttf
.vscode
.idea
dist
/public
/docs
.husky
/bin
.eslintrc.js
prettier.config.js
/src/mock/*

# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*

.DS_Store
dist-ssr
*.local

/cypress/videos/
/cypress/screenshots/

# Editor directories and files
.vscode
!.vscode/extensions.json
.idea
*.suo
*.njsproj
*.sln
*.sw?

components.d.ts
.prettiercjs.js文件内容:

module.exports = {
 // 一行最多多少字符
 printWidth: 80,
 // 使用2个空格缩进
 tabWidth: 2,
 // 使用tab缩进,不使用空格
 useTabs: true,
 // 行尾需要分号
 semi: true,
 // 使用单引号
 singleQuote: true,
 // 对象的key仅在必要时使用引号
 quoteProps: 'as-needed',
 // jsx不使用单引号,而使用双引号
 jsxSingleQuote: false,
 // 尾随逗号
 trailingComma: 'es5',
 // 大括号内的收尾需要空格
 bracketSpacing: true,
 // 箭头函数,只有一个参数的时候,也需要括号
 arrowParens: 'always',
 // 每个文件格式化的范围是文件的全部内容
 rangeStart: 0,
 rangeEnd: Infinity,
 // 不需要写文件开头的@prettier
 requirePragma: false,
 // 不需要自动在文件开头插入@prettier
 insertPragma: false,
 // 使用默认的折行标准
 proseWrap: 'always',
 // 根据显示样式决定html要不要折行
 htmlWhitespaceSensitivity: 'css',
 // 换行符使用lf
 endOfLine: 'lf',
};
.prettierignore文件内容:

/dist/*
.local
.output.js
/node_modules/**
src/.DS_Store

**/*.svg
**/*.sh

/public/*
components.d.ts

Husky、lint-staged、commitlint 功能添加

husky 是一个未 git 客户端增加 hook 的工具,在一些 git 操作之前自动触发的函数

https://typicode.github.io/husky/#/open in new window

如果我们希望在检测错误的同时,自动修复 eslint 语法错误,就可以通过后面钩子实现

lint-staged 过滤出 git 代码暂存区(被 git add 的文件)的工具,将所有暂存文件 的列表传递给任务

commitlint 是对我们 git commit 提交的注释进行校验的工具

常用的 git hooks

pre-commit:由 git commit 调用,在 commit 之前执行 commit-msg:由 git commit 或 git merge 调用 pre-merge-commit:由 git merge 调用,在 merge 之前执行 pre-push:被 git push 调用,在 git push 之前执行,防止进行推送

pnpm install husky lint-staged @commitlint/config-conventional @commitlint/cli -D

配置package.json文件
(新项目需要先 git init 一下)
"prepare": "husky install"

执行 npm run prepare, 将husky安装完毕

----------

后面就可以添加各种 git hooks 钩子
pre-commit 一般添加的是lint-staged,去对git暂存区的代码做一些格式化的操作
npx husky add .husky/pre-commit "npx lint-staged"
echo "npx lint-staged" > .husky/pre-commit
add: 追加
set: 直接覆盖

----------

lint-staged对add之后,暂存区里面的文件进行格式化修复等工作
pnpm install lint-staged -D

package.json文件中,添加

"lint-staged": {
    "*.{js,jsx,vue,ts,tsx}": [
      "npm run lint",
      "npm run prettier-format"
    ]
  }

----------

pnpm install @commitlint/config-conventional @commitlint/cli -D
安装这两个库,然后新建一个config文件(commitlint.config.cjs)

添加到git钩子里
npx husky add .husky/commit-msg "npx --no -- commitlint --edit ${1}"
echo "npx --no -- commitlint --edit ${1}" > .husky/commit-msg
通过一个命令添加钩子

使用git commit -m "提交说明",进行提交,提交说明应尽量清晰明了,说明本次提交的目的
推荐使用Angular规范,这是目前使用最广的写法
commitlint-config.cjs文件内容:

module.exports = {
 extends: ['@commitlint/config-conventional'],
 rules: {
  'type-enum': [
   2,
   'always',
   [
    // 编译相关的修改,例如发布版本,对项目构建或者依赖的改动
    'build',
    // 新功能(feature)
    'feat',
    // 修复bug
    'fix',
    // 更新某功能
    'update',
    // 重构
    'refactor',
    // 文档
    'docs',
    // 构建过程或者辅助工具的变动,如增加依赖库等
    'chore',
    // 不影响代码运行的变动
    'style',
    // 撤销commit,回滚到上一个版本
    'revert',
    // 性能优化
    'perf',
    // 测试(单元,集成测试)
    'test',
   ],
  ],
  'type-case': [0],
  'type-empty': [0],
  'scope-empty': [0],
  'scope-case': [0],
  'subject-full-stop': [0, 'never'],
  'subject-case': [0, 'never'],
  'header-max-length': [0, 'always', 74],
 },
};

stylelint 钩子

CSS 检查器(linter),帮助我们规避 CSS 代码中的错误并保持一致的编码风格

https://stylelint.io/user-guide/get-started

stylelint CSS代码检查器(linter)

1. 安装vscode插件,Stylelint
2. 修改settings.json,添加下面代码
{
	"editor.codeActionsOnSave": {
    "source.fixAll.stylelint": true
  },
	"stylelint.validate": [
		"css",
		"less",
		"scss",
		"vue"
	],
}
3. 安装项目需要的校验库,(常见的规则包)
pnpm install stylelint stylelint-config-standard -D
pnpm install stylelint  stylelint-config-standard stylelint-config-html stylelint-order stylelint-scss -D

4. 根目录下建立 .stylelintrc.cjs
module.exports = {
	extends: ['stylelint-config-standard'],
};

这是一个标准样式库,也可以自动添加一些样式规则在stylelintrc.cjs文件里面

5. 执行 npx stylelint "**/*.css"
发现项目里面的style.css全局样式文件,报错很多
具体到对应的文件,按ctrl+s就会执行自动格式化我们在setting.json里面添加的语句(第2步)

6. 增加vue里面的样式支持(附带less和scss的支持)
对less的支持
pnpm install stylelint-less stylelint-config-recommended-less -D

对scss的支持
pnpm install stylelint-scss stylelint-config-recommended-scss postcss -D


pnpm install postcss-html stylelint-config-standard-scss stylelint-config-recommended-vue postcss -D (对vue里面样式的支持,vue的样式需要依赖前面这个库)

Vite也同时提供了对 .scss .sass .less .styl .stylus 文件的内置支持,不需要再安装特定插件和预处理器

extends: [
	"stylelint-config-standard",
	"stylelint-config-recommended-less",
	"stylelint-config-recommended-scss",
	"stylelint-config-recommended-vue"
]

scss的extends
extends:[
	"stylelint-config-standard-scss",
	"stylelint-config-recommended-vue/scss"
]

7. package.json文件添加
"lint:css": "stylelint **/*.{vue,css,sass,scss} --fix"

8. 给vite添加插件
pnpm install vite-plugin-stylelint -D

修改vite.config.js文件
import stylelitPlugin from 'vite-plugin-stylelint';

plugins: [... stylelitPlugin()],

9. 添加到lint-staged里面,在暂存区对文件进行格式化
"lint-staged": {
    "*.{js,jsx,vue,ts,tsx}": [
      "npm run lint",
      "npm run prettier-format"
    ],
    "*.{vue,less,css,scss,sass}": [
      "npm run lint:css"
    ]
  }

10. 添加一个.stylelintignore文件
/dist/*
/public/*

11. .stylelintrc.cjs内部的其他配置
module.exports = {
	extends: ['stylelint-config-standard', 'stylelint-config-recommended-vue'],
	overrides: [
		// 若项目中存在scss文件,添加以下配置
		{
			files: ['*.scss', '**/*.scss'],
			customSyntax: 'postcss-scss',
			extends: ['stylelint-config-recommended-scss'],
		},
		// 若项目中存在less文件,添加以下配置
		{
			files: ['*.less', '**/*.less'],
			customSyntax: 'postcss-less',
			extends: ['stylelint-config-recommended-less'],
		},
	],
};

环境变量和模式

https://cn.vitejs.dev/guide/env-and-mode.html#modes

开发环境 dev

测试使用 预发环境,pre

生产环境,pro

在package.json文件里面写上对应的脚本

"build:pre": "vue-tsc --noEmit && vite build --mode staging",
"build:pro": "vue-tsc --noEmit && vite build --mode production"

新建文件
.env
.env.development
.env.staging
.env.production

项目配置的内容
文件内容 VITE_BASE_URL = 'http://yewu-pre.jd.com/api'

demo


上次编辑于: