第四章 项目环境配置(二)——代码规范

4.2 代码规范

4.2.1 配置 editorconfig

EditorConfig 官网

EditorConfig 有助于为不同 IDE 编辑器上处理同一项目的多个开发人员维护一致的编码风格。

  1. 安装 EditorConfig for VS Code 插件。

image-20240109165549023

  1. 在项目根目录下新建 .editorconfig 文件。

    Vue2 官网使用的文件,Vue3 官网未使用。

    image-20240109170053379

    # http://editorconfig.org
    
    root = true
    
    [*] # 表示所有文件适用
    charset = utf-8 # 设置文件字符集为 utf-8
    indent_style = space # 缩进风格(tab | space)
    indent_size = 2 # 缩进大小
    end_of_line = lf # 控制换行类型(lf | cr | crlf)
    trim_trailing_whitespace = true # 去除行首的任意空白字符
    insert_final_newline = true # 始终在文件末尾插入一个新行
    
    [*.md] # 表示仅 md 文件适用以下规则
    max_line_length = off
    trim_trailing_whitespace = false
    

4.2.2 配置 Prettier

Prettier 官网

  1. 安装 Prettier

    npm install -D prettier
    

    新增的开发依赖

    "devDependencies": {
         "prettier": "^3.1.1",  // ++
    }
    
  2. 创建 .prettierrc.cjs 文件

    .prettierrc.prettierrc.json.prettierrc.yml.prettierrc.yaml.prettierrc.json5.prettierrc.jsprettier.config.js.prettierrc.mjsprettier.config.mjs.prettierrc.cjsprettier.config.cjs.prettierrc.toml 均可识别,详细参考官网 https://www.prettier.cn/docs/configuration.html。

    image-20240109174145920

    module.exports = {
    	// 一行最多多少个字符
    	printWidth: 150,
    	// 指定每个缩进级别的空格数
    	tabWidth: 2,
    	// 使用制表符而不是空格缩进行
    	useTabs: true,
    	// 在语句末尾打印分号
    	semi: true,
    	// 使用单引号而不是双引号
    	singleQuote: true,
    	// 更改引用对象属性的时间 可选值"<as-needed|consistent|preserve>"
    	quoteProps: 'as-needed',
    	// 在JSX中使用单引号而不是双引号
    	jsxSingleQuote: false,
    	// 多行时尽可能打印尾随逗号。(例如,单行数组永远不会出现逗号结尾。) 可选值"<none|es5|all>",默认none
    	trailingComma: 'es5',
    	// 在对象文字中的括号之间打印空格
    	bracketSpacing: true,
    	// jsx 标签的反尖括号需要换行
    	jsxBracketSameLine: false,
    	// 在单独的箭头函数参数周围包括括号 always:(x) => x \ avoid:x => x
    	arrowParens: 'always',
    	// 这两个选项可用于格式化以给定字符偏移量(分别包括和不包括)开始和结束的代码
    	rangeStart: 0,
    	rangeEnd: Infinity,
    	// 指定要使用的解析器,不需要写文件开头的 @prettier
    	requirePragma: false,
    	// 不需要自动在文件开头插入 @prettier
    	insertPragma: false,
    	// 使用默认的折行标准 always\never\preserve
    	proseWrap: 'preserve',
    	// 指定HTML文件的全局空格敏感度 css\strict\ignore
    	htmlWhitespaceSensitivity: 'css',
    	// Vue文件脚本和样式标签缩进
    	vueIndentScriptAndStyle: false,
    	// 换行符使用 lf 结尾是 可选值"<auto|lf|crlf|cr>"
    	endOfLine: 'lf',
    };
    
  3. 在根目录下新建 .prettierignore 文件,忽略对部分文件的格式化。

    /dist/*
    /html/*
    .local
    /node_modules/**
    
    **/*.svg
    **/*.sh
    
    /public/*
    
  4. 检查修改。

    • 检查

      npx prettier . --check
      
    • 修改

      npx prettier . --write
      

      image-20240109181230341

  5. 保存时自动格式化

    • 手动保存(Ctrl+S)时会自动格式化。
    • 参照 3.3.1 节,设置 onFocusChangeonWindowChange,自动保存时会自动格式化。

    设置 afterDelay,自动保存不会生效,参阅 prettier-vscode#502#613 两个 issues,原因是 Visual Studio Code"files.autoSave": "afterDelay""editor.formatOnSave": true 这两个配置不能一起使用。

    建议相关参数修改后,重新启动 IDE

4.2.3 配置 ESLint

ESLint 官网

ESLint 用于查找并修复 JavaScript 代码中的问题

  1. 安装和配置 ESLint

    npm init @eslint/config
    
    • 选项参考

      $ npm init @eslint/config
      Need to install the following packages:
      @eslint/create-config@0.4.6
      Ok to proceed? (y) y
      √ How would you like to use ESLint? · problems
      √ What type of modules does your project use? · esm
      √ Which framework does your project use? · vue
      √ Does your project use TypeScript? · No / Yes
      √ Where does your code run? · browser
      √ What format do you want your config file to be in? · JavaScript
      Local ESLint installation not found.
      The config that you've selected requires the following dependencies:
      
      @typescript-eslint/eslint-plugin@latest eslint-plugin-vue@latest @typescript-eslint/parser@latest eslint@latest
      √ Would you like to install them now? · No / Yes
      √ Which package manager do you want to use? · npm
      Installing @typescript-eslint/eslint-plugin@latest, eslint-plugin-vue@latest, @typescript-eslint/parser@latest, eslint@latest
      
      added 138 packages in 13s
      Successfully created .eslintrc.cjs file in E:\MyProjects\admin\yc-admin
      
    • 当前 package.json 文件:

      {
         "name": "yc-admin",
         "private": true,
         "version": "0.0.0",
         "type": "module",
         "scripts": {
            "dev": "vite",
            "build": "vue-tsc && vite build",
            "preview": "vite preview"
         },
         "dependencies": {
            "vue": "^3.4.5"
         },
         "devDependencies": {
            "@typescript-eslint/eslint-plugin": "^6.18.0",
            "@typescript-eslint/parser": "^6.18.0",
            "@vitejs/plugin-vue": "^5.0.0",
            "eslint": "^8.56.0",
            "eslint-plugin-vue": "^9.19.2",
            "typescript": "^5.2.2",
            "vite": "^5.0.8",
            "vue-tsc": "^1.8.27"
         }
      }
      
    • 生成的 .eslintrc.cjs 文件:

      module.exports = {
         env: {
            browser: true,
            es2021: true,
         },
         extends: [
            "eslint:recommended",
            "plugin:@typescript-eslint/recommended",
            "plugin:vue/vue3-essential",
         ],
         overrides: [
            {
              env: {
                 node: true,
              },
              files: [".eslintrc.{js,cjs}"],
              parserOptions: {
                 sourceType: "script",
              },
            },
         ],
         parserOptions: {
            ecmaVersion: "latest",
            parser: "@typescript-eslint/parser",
            sourceType: "module",
         },
         plugins: ["@typescript-eslint", "vue"],
         rules: {},
      };
      

      因系统默认采用ES6模式,但Eslint是以CommonJs模式读取配置文件,配置文件明确指出是CommonJs模式,即.eslintrc.cjs,否则Eslint无法读取配置文件。
      也可将package.json中的type删除(不推荐),则系统默认采用CommonJs模式。

  2. 在根目录新建 .eslintignore 文件

    *.sh
    node_modules
    lib
    *.md
    *.scss
    *.woff
    *.ttf
    .vscode
    .idea
    dist
    mock
    public
    bin
    build
    config
    index.html
    src/assets
    
  3. 安装 ESLint 插件

    image-20240109202428104

    ESLint 开始工作

    image-20240109202239768

  4. 解决 ESLintPrettier 之间的冲突

    • 安装 eslint-config-prettier

      npm install --save-dev eslint-config-prettier,eslint-plugin-prettier
      
    • eslint-config-prettier 添加到 ESLint 的配置 “extends” 数组中,确保把它放在最后,这样它就有机会覆盖其他配置。

      "extends": [
          "eslint:recommended",
          "plugin:@typescript-eslint/recommended",
          "plugin:vue/vue3-essential",
          "prettier",
          "plugin:prettier/recommended"
      ],
      
    • 测试生效。

      image-20240110180606690

请分别参阅 eslint-config-prettier 官网eslint-plugin-prettier 官网eslint-plugin-vue 官网

eslint-config-prettiereslint-plugin-prettier 是用于与 ESLintPrettier 集成的两个不同的包。

  • eslint-config-prettier :这是一个 ESLint 配置规则的包,它将禁用与 Prettier 冲突的 ESLint 规则。使用 eslint-config-prettier 可以确保 ESLint 规则与 Prettier 的代码格式化规则保持一致,避免二者之间的冲突。

  • eslint-plugin-prettier :这是一个 ESLint 插件,它将 Prettier 应用到 ESLint 中。它会使用 Prettier 来格式化代码,并将格式化结果作为 ESLint 的一项规则来检查代码。使用 eslint-plugin-prettier 可以在代码检查的同时,自动格式化代码,使其符合 Prettier 的规则。

通常情况下,我们需要同时安装这两个包来实现 ESLintPrettier 的集成。首先,使用 eslint-config-prettier 禁用与 Prettier 冲突的 ESLint 规则,然后使用 eslint-plugin-prettierPrettier 应用到 ESLint 中,以便在代码检查时自动格式化代码。

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值