Vite + Vue3 项目配置 ESLint 规范和 Jest 单元测试

5,380 阅读3分钟

搭建基础项目

首先用 vite 搭建一个基础的项目模板:

yarn create vite eslintJest --template vue-ts

cd eslintJest

yarn

安装完依赖就可以启动了:

image.png

下面就可以配置 eslint 和 jest 了。

ESLint 配置

安装初始依赖包
yarn add eslint eslint-plugin-vue -D
在 package.json 添加 scripts 命令
{
    "scripts" {
        // 检查 src 目录下所有js、vue、ts文件,--fix 是可以自动修复部分错误
        "lint": "eslint src/**/*.{js,vue,ts} --fix",
        // 初始化配置 .eslintrc.js 配置文件
        "lint:create": "eslint --init"
    }
}
生成 .eslintrc.js 文件

执行 yarn lint:create

image.png

到这一步的话,如果用 npm 安装上面三个包,直接点 Yes,否则可以点 No,结束后用 yarn 或 cnpm 安装,我这里点的不安装,结束后再用 yarn 安装:

yarn add eslint-plugin-vue@latest @typescript-eslint/eslint-plugin@latest @typescript-eslint/parser@latest -D

这安装完成之后 .eslintrc.js 就已经生成了。

image.png

规范配置

到这里我们就可以在 rules 属性内添加具体开发规范了,具体的配置可以去 eslint 官网查看:eslint.org/docs/rules/

{
    // others ...
    "rules": {
        'vue/script-setup-uses-vars': 'error',
        "indent": [ "error", 2],
        "linebreak-style": [ "error", "windows" ],
        "quotes": [ "error", "single" ],
        "semi": [ "error", "never" ],
        "object-shorthand": ["error", "always"],
        "array-bracket-spacing": [
          "error",
          "always",
          { 
            "objectsInArrays": false,
            "arraysInArrays": false
          }
        ],
        "array-callback-return": "error",
        "arrow-spacing": "error",
        "block-scoped-var": "error",
        "block-spacing": "error",
        "brace-style": ["error", "1tbs", { "allowSingleLine": true }],
        "camelcase": "error",
        "comma-spacing": ["error", { "before": false, "after": true }],
        "comma-style": ["error", "last"],
        "computed-property-spacing": ["error", "never"],
        "consistent-this": ["error", "that"],
        "constructor-super": "error",
        "curly": "error",
        "default-case": "error",
        "dot-location": ["error", "property"],
        "dot-notation": "error",
        "eol-last": ["error", "always"],
        "eqeqeq": ["error", "always"],
        "for-direction": "warn",
        "func-call-spacing": ["error", "never"],
        "func-names": ["warn", "as-needed"],
        "function-paren-newline": ["error", { "minItems": 4 }],
        "getter-return": ["error", { "allowImplicit": true }],
        "guard-for-in": "warn",
        "implicit-arrow-linebreak": ["warn", "beside"],
        "jsx-quotes": ["error", "prefer-single"],
        "key-spacing": [ "error", {
            "beforeColon": false,
            "align": "colon"
        }],
        "keyword-spacing": ["error", {
          "before": true,
          "after": true
        }],
        "lines-around-comment": ["warn", { "beforeBlockComment": true }],
        "new-cap": "warn",
        "no-await-in-loop": "error",
        "no-buffer-constructor": "error",
        "no-cond-assign": "error",
        "no-empty": "warn",
        "no-constant-condition": "warn",
        "vue/no-multiple-template-root": "off"
    }
}
其它 vue3 相关的配置修改

这里我们需要用到 eslint-plugin-vue 这个插件 ,最主要的有三点:

  1. 添加 parser 属性配置
    {
        // others ...
        "parser": "vue-eslint-parser"
    }
    
  2. extends 添加 vue3 的配置
    {
        // others ...
        extends: {
            // others ...
            "plugin:vue/vue3-recommended"
        }
    }
    
  3. 关于 setup SFC 的一些关键词检验进行全局变量配置
    {
        // others ...
        globals: {
            "defineProps": "readonly",
             "defineEmits": "readonly",
             "defineExpose": "readonly",
             "withDefaults": "readonly"
        }
    }
    

到这里 ESLint 的配置基本就结束了,下面来测试一下:

在 App.vue 加上一段错误的代码

image.png

直接执行检查命令是 OK 的,还有一个是在运行阶段的 ESLint 的检查

image.png

这里发现 yarn dev 是并没有检查规范的,这里还需要添加一个 vite 的 eslint 插件。

yarn add vite-plugin-eslint -D

然后在 vite.config.ts 文件内的 plugins 内加上:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import eslintPlugin from 'vite-plugin-eslint'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    eslintPlugin({
      include: ['src/**/*.js', 'src/**/*.vue', 'src/**/*.ts']
    })
  ]
})

然后再次运行:

image.png

这里已经出来了。

Jest 配置

npm 包安装

首先安装需要的包

yarn add @babel/core @babel/preset-env @testing-library/jest-dom @types/jest @vue/test-utils@next @babel/preset-typescript @vue/babel-plugin-jsx vue-jest@next -D

// 下面三个包的版本需要固定,有些版本和 vue-test 的对应不上,则会出错
yarn add babel-jest@26.0.0 jest@26.0.0 ts-jest@26.4.4 -D
jest.config.js

新建一个 jest.config.js 的配置文件

const path = require('path')

module.exports = {
  rootDir: path.resolve(__dirname),
  clearMocks: true,
  coverageDirectory: 'coverage',
  coverageProvider: 'v8',
  moduleFileExtensions: ['vue', 'js', 'json', 'jsx', 'ts', 'tsx', 'node'],
  // 别名设置
  moduleNameMapper: {
    '@/(.*)$': '<rootDir>/src/components/$1'
  },
  preset: 'ts-jest',
  testEnvironment: 'jsdom',
  // 测试文件
  testMatch: ['<rootDir>/src/__tests__/**/*.spec.(ts|tsx|js)'],
  testPathIgnorePatterns: ['/node_modules/'],
  moduleFileExtensions: ['js', 'json', 'ts', 'tsx'],
  
  transform: {
    '^.+\\.vue$': 'vue-jest',
    '^.+\\.(ts|tsx|js|jsx)$': [
      'babel-jest', {
        presets: [
          ['@babel/preset-env', { targets: { node: 'current' } }],
          ['@babel/preset-typescript']
        ],
        plugins: ['@vue/babel-plugin-jsx']
      }
    ]
  }
}
添加 scripts 命令

在 package.json 添加 scripts 命令

{
    // others ...
    "scripts": {
        // others ...
        "test": "jest"
    }
}
测试

到这里 Jest 的配置就完成了,新建一个测试文件来跑下

// src/__tests__/helloworld/index.spec.js
import { mount } from '@vue/test-utils'
import HelloWorld from '@/HelloWorld.vue'

test('displays message', async () => {
  const wrapper = await mount(HelloWorld, {
    props: {
      msg: 'test msg'
    }
  })

  // Assert the rendered text of the component
  expect(wrapper.find('h1').text()).toBe('test msg')
  expect(wrapper.find('button').text()).toBe('count is: 0')
  await wrapper.find('button').trigger('click')
  expect(wrapper.find('button').text()).toBe('count is: 1')
})

image.png

下面这个是用 vscode 的 Jest Runner 插件跑的

image.png