vue3项目+TypeScript前端项目—— vue3搭建项目+eslint+husky

今天来带大家从0开始搭建一个vue3版本的后台管理系统。一个项目要有统一的规范,需要使用eslint+stylelint+prettier来对我们的代码质量做检测和修复,需要使用husky来做commit拦截,需要使用commitlint来统一提交规范,需要使用preinstall来统一包管理工具。

下面我们就用这一套规范来初始化我们的项目,集成一个规范的模版。

1.1 环境准备

  • node v16.14.2
  • pnpm 8.0.0

1.2初始化项目

本项目使用vite进行构建,vite官方中文文档参考:cn.vitejs.dev/guide/

pnpm:performant npm ,意味“高性能的 npm”。pnpm由npm/yarn衍生而来,解决了npm/yarn内部潜在的bug,极大的优化了性能,扩展了使用场景。被誉为“最先进的包管理工具”

所以,我们也试一试pmpm有多好用,一起来用一用吧!

①安装pnpm

pnpm安装指令:npm i -g pnpm
在这里插入图片描述

②项目初始化

在指定的文件夹内新建一个文件夹,进入后运行创建项目的命令
项目初始化命令:pnpm create vite

报错了,如下:
在这里插入图片描述
根据错误提示信息,是由于原淘宝npm镜像地址:“ https://registry.npm.taobao.org ” 的证书失效
手动修改Dockerfile的构建指令,配置 registry 即可,将原:

RUN npm config set registry https://registry.npm.taobao.org

修改为:

RUN npm config set registry https://registry.npmmirror.com

再次运行,成功了。
在这里插入图片描述

③安装依赖

进入到项目根目录pnpm install安装全部依赖。

④运行程序

安装完依赖运行程序:pnpm run dev

1.3 项目配置

1.3.1 运行后自动打开浏览器

package.json里面的dev添加--open
在这里插入图片描述

1.3.2 eslint配置 —— js代码质量

eslint中文官网:http://eslint.cn/

这是一个插件化的javascript代码检测工具,保证代码的质量

①首先安装eslint

pnpm i eslint -D

②生成配置文件:.eslint.cjs

npx eslint --init

在这里插入图片描述
运行成功,我们可以看到项目的根路径会多一个.eslintrc.cjs的文件

③详看.eslint.cjs配置文件

module.exports = {
   
   //运行环境
    "env": {
    
        "browser": true,//浏览器端
        "es2021": true,//es2021
    },
    //规则继承
    "extends": [ 
       //全部规则默认是关闭的,这个配置项开启推荐规则,推荐规则参照文档
       //比如:函数不能重名、对象不能出现重复key
        "eslint:recommended",
        //vue3语法规则
        "plugin:vue/vue3-essential",
        //ts语法规则
        "plugin:@typescript-eslint/recommended"
    ],
    //要为特定类型的文件指定处理器
    "overrides": [
    ],
    //指定解析器:解析器
    //Esprima 默认解析器
    //Babel-ESLint babel解析器
    //@typescript-eslint/parser ts解析器
    "parser": "@typescript-eslint/parser",
    //指定解析器选项
    "parserOptions": {
   
        "ecmaVersion": "latest",//校验ECMA最新版本
        "sourceType": "module"//设置为"script"(默认),或者"module"代码在ECMAScript模块中
    },
    //ESLint支持使用第三方插件。在使用插件之前,您必须使用npm安装它
    //该eslint-plugin-前缀可以从插件名称被省略
    "plugins": [
        "vue",
        "@typescript-eslint"
    ],
    //eslint规则
    "rules": {
   
    }
}

④ vue3环境代码校验插件

# 让所有与prettier规则存在冲突的Eslint rules失效,并使用prettier进行代码检查
"eslint-config-prettier": "^8.6.0",
"eslint-plugin-import": "^2.27.5",
"eslint-plugin-node": "^11.1.0",
# 运行更漂亮的Eslint,使prettier规则优先级更高,Eslint优先级低
"eslint-plugin-prettier": "^4.2.1",
# vue.js的Eslint插件(查找vue语法错误,发现错误指令,查找违规风格指南
"eslint-plugin-vue": "^9.9.0",
# 该解析器允许使用Eslint校验所有babel code
"@babel/eslint-parser": "^7.19.1",

安装指令
pnpm install -D eslint-plugin-import eslint-plugin-vue eslint-plugin-node eslint-plugin-prettier eslint-config-prettier eslint-plugin-node @babel/eslint-parser

⑤ 修改.eslintrc.cjs配置文件

安装完第三步的插件,需要修改.eslintrc.cjs配置文件,直接拷贝下面的即可

// @see https://eslint.bootcss.com/docs/rules/

module.exports = {
   
  env: {
   
    browser: true,
    es2021: true,
    node: true,
    jest: true,
  },
  /* 指定如何解析语法 */
  parser: 'vue-eslint-parser',
  /** 优先级低于 parse 的语法解析配置 */
  parserOptions: {
   
    ecmaVersion: 'latest',
    sourceType: 'module',
    parser: '@typescript-eslint/parser',
    jsxPragma: 'React',
    ecmaFeatures: {
   
      jsx: true,
    },
  },
  /* 继承已有的规则 */
  extends: [
    'eslint:recommended',
    'plugin:vue/vue3-essential',
    'plugin:@typescript-eslint/recommended',
    'plugin:prettier/recommended',
  ],
  plugins: ['vue', '@typescript-eslint'],
  /*
   * "off" 或 0    ==>  关闭规则
   * "warn" 或 1   ==>  打开的规则作为警告(不影响代码执行)
   * "error" 或 2  ==>  规则作为一个错误(代码不能执行,界面报错)
   */
  rules: {
   
    // eslint(https://eslint.bootcss.com/docs/rules/)
    'no-var': 'error', // 要求使用 let 或 const 而不是 var
    'no-multiple-empty-lines': ['warn', {
    max: 1 }], // 不允许多个空行
    'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off',
    'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
    'no-unexpected-multiline': 'error', // 禁止空余的多行
    'no-useless-escape': 'off', // 禁止不必要的转义字符

    // typeScript (https://typescript-eslint.io/rules)
    '@typescript-eslint/no-unused-vars': 'error', // 禁止定义未使用的变量
    '@typescript-eslint/prefer-ts-expect-error': 'error', // 禁止使用 @ts-ignore
    '@typescript-eslint/no-explicit-any': 'off', // 禁止使用 any 类型
    '@typescript-eslint/no-non-null-assertion': 'off',
    '@typescript-eslint/no-namespace': 'off', // 禁止使用自定义 TypeScript 模块和命名空间。
    '@typescript-eslint/semi': 'off',

    // eslint-plugin-vue (https://eslint.vuejs.org/rules/)
    'vue/multi-word-component-names': 'off', // 要求组件名称始终为 “-” 链接的单词
    'vue/script-setup-uses-vars': 'error', // 防止<script setup>使用的变量<template>被标记为未使用
    'vue/no-mutating-props': 'off', // 不允许组件 prop的改变
    'vue/attribute-hyphenation': 'off', // 对模板中的自定义组件强制执行属性命名样式
  },
}

eslintignore忽略文件

根目录创建eslintignore忽略文件

dist
node_modules

⑦ 运行脚本

package.jsonscript下面添加两个运行脚本

"scripts": {
   
    "lint": "eslint src", 
    "fix": "eslint src --fix",
}

在这里插入图片描述

lint 用于报错提示,给出校验提示
fix用于根据报错,修复

示例

运行pnpm lint就可以校验是否有错误的文件,及其位置
在这里插入图片描述
运行pnpm fix直接帮我们修复了
在这里插入图片描述

1.3.3 配置prettier —— 代码美观

有了eslint,为什么还要有prettier?eslint针对的是javascript,他是一个检测工具,包含js语法以及少部分格式问题,在eslint看来,语法对了就能保证代码正常运行,格式问题属于其次;
而prettier属于格式化工具,它看不惯格式不统一,所以它就把eslint没干好的事接着干,另外,prettier支持包含js在内的多种语言。

总结起来,eslint和prettier这俩兄弟一个保证js代码质量,一个保证代码美观。

①安装依赖包

pnpm install -D eslint-plugin-prettier prettier eslint-config-prettier

.prettierrc.json添加规则

项目根目录创建prettierrc.json文件

“singleQuote”: true, //字符串单引号
“semi”: false,//语句末尾分号不要了
“tabWidth”: 2 //缩进占两个tab

{
   
  "singleQuote": true,
  "semi": false,
  "bracketSpacing": true,
  "htmlWhitespaceSensitivity": "ignore",
  "endOfLine": "auto",
  "trailingComma": "all",
  "tabWidth": 2
}

.prettierignore忽略文件

项目根目录创建.prettierignore文件

/dist/*
/html/*
.local
/node_modules/**
**/*.svg
**/*.sh
/public/*

通过pnpm run lint去检测语法,如果出现不规范格式,通过pnpm run fix 修改
在这里插入图片描述
在这里插入图片描述

1.3.4 配置stylelint —— css 格式化

stylelint为css的lint工具。可格式化css代码,检查css语法错误与不合理的写法,指定css书写顺序等。

①安装依赖

我们的项目中使用scss作为预处理器,安装以下依赖:

pnpm add sass sass-loader stylelint postcss postcss-scss postcss-html stylelint-config-prettier stylelint-config-recess-order stylelint-config-recommended-scss stylelint-config-standard stylelint-config-standard-vue stylelint-scss stylelint-order stylelint-config-standard-scss -D

.stylelintrc.cjs配置文件

官网:https://stylelint.bootcss.com/
项目根目录创建.stylelintrc.cjs配置文件

// @see https://stylelint.bootcss.com/

module.exports = {
   
  extends: [
    'stylelint-config-standard', // 配置stylelint拓展插件
    'stylelint-config-html/vue', // 配置 vue 中 template 样式格式化
    'stylelint-config-standard-scss', // 配置stylelint scss插件
    'stylelint-config-recommended-vue/scss', // 配置 vue 中 scss 样式格式化
    'stylelint-config-recess-order', // 配置stylelint css属性书写顺序插件,
    'stylelint-config-prettier', // 配置stylelint和prettier兼容
  ],
  overrides: [
    {
   
      files: ['**/*.(scss|css|vue|html)'],
      customSyntax: 'postcss-scss',
    },
    {
   
      files: ['**/*.(html|vue)'],
      customSyntax: 'postcss-html',
    },
  ],
  ignoreFiles: [
    '**/*.js',
    '**/*.jsx',
    '**/*.tsx',
    '**/*.ts',
    '**/*.json',
    '**/*.md',
    '**/*.yaml',
  ],
  /**
   * null  => 关闭该规则
   * always => 必须
   */
  rules: {
   
    'value-keyword-case': null, // 在 css 中使用 v-bind,不报错
    'no-descending-specificity': null, // 禁止在具有较高优先级的选择器后出现被其覆盖的较低优先级的选择器
    'function-url-quotes': 'always', // 要求或禁止 URL 的引号 "always(必须加上引号)"|"never(没有引号)"
    'no-empty-source': null, // 关闭禁止空源码
    'selector-class-pattern': null, // 关闭强制选择器类名的格式
    'property-no-unknown': null, // 禁止未知的属性(true 为不允许)
    'block-opening-brace-space-before': 'always', //大括号之前必须有一个空格或不能有空白符
    'value-no-vendor-prefix': null, // 关闭 属性值前缀 --webkit-box
    'property-no-vendor-prefix': null, // 关闭 属性前缀 -webkit-mask
    'selector-pseudo-class-no-unknown': [
      // 不允许未知的选择器
      true,
      {
   
        ignorePseudoClasses: ['global', 'v-deep', 'deep'], // 忽略属性,修改element默认样式的时候能使用到
      },
    ],
  },
}

.stylelintignore忽略文件

/node_modules/*
/dist/*
/html/*
/public/*

④运行脚本

"scripts": {
   
	"lint:style": "stylelint src/**/*.{css,scss,vue} --cache --fix"
}

=============================================================================

1.3.5 统一格式化js和css,html代码

最后配置统一的prettier来格式化我们的js和css,html代码

 "scripts": {
   
    "dev": "vite --open",
    "build": "vue-tsc && vite build",
    "preview": "vite preview",
    "lint": "eslint src",
    "fix": "eslint src --fix",
    "format": "prettier --write \"./**/*.{html,vue,ts,js,json,md}\"",
    "lint:eslint": "eslint src/**/*.{ts,vue} --cache --fix",
    "lint:style": "stylelint src/**/*.{css,scss,vue} --cache --fix"
  },

当我们运行pnpm run format的时候,会把代码直接格式化

示例:

在这里插入图片描述
运行pnpm run format,运行成功
在这里插入图片描述
会多这么几个文件:
在这里插入图片描述

1.3.6 配置husky

在上面我们已经集成好了我们代码校验工具,但是需要每次手动的去执行命令才会格式化我们的代码。如果有人没有格式化就提交了远程仓库中,那这个规范就没什么用。所以我们需要强制让开发人员按照代码规范来提交。

要做到这件事情,就需要利用husky在代码提交之前触发git hook(git在客户端的钩子),然后执行pnpm run format来自动的格式化我们的代码。

①安装

安装husky

pnpm install -D husky

②执行

npx husky-init

③添加命令

会在根目录下生成个一个.husky目录,在这个目录下面会有一个pre-commit文件,这个文件里面的命令在我们执行commit的时候就会执行

.husky/pre-commit文件添加如下命令:

#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
pnpm run format

在这里插入图片描述

当我们对代码进行commit操作的时候,就会执行命令,对代码进行格式化,然后再提交。

④示例

  1. 在本地代码新建本地仓库
    在本地代码下运行git init
    然后文件的根目录会多一个.git的文件

  2. 建立远程的仓库

  3. 本地仓库与远程仓库关联

git remote add origin https://xxx.git
git add .
git commit -m "first commit"
git push -u origin "master"
  1. 这样的话,你的兄弟们就可以随意提交代码,然后你拉的就是那些没格式化的代码,你前面做的一切做的一切都白费了。
    在这里插入图片描述
    所以我们需要做的就是强制让开发人员按照代码规范来提交。那么就用到了husky

  2. 安装husky,执行npx husky-init,添加pnpm run format

  3. 这样commit提交代码的时候,就会自动运行pnpm run format

把这样的一段提交上去
在这里插入图片描述

看到没有,commit的时候就自动format
在这里插入图片描述
我们去看下远程仓库

1.3.7 配置commitlint

对于我们的commit信息,也是有统一规范的,不能随便写,要让每个人都按照统一的标准来执行,我们可以利用commitlint来实现。

①安装

pnpm add @commitlint/config-conventional @commitlint/cli -D

②新建.commitlint.config.cjs

添加配置文件,新建.commitlint.config.cjs(注意是cjs),然后添加下面的代码:

module.exports = {
   
  extends: ['@commitlint/config-conventional'],
  // 校验规则
  rules: {
   
    'type-enum': [
      2,
      'always',
      [
        'feat',
        'fix',
        'docs',
        'style',
        'refactor',
        'perf',
        'test',
        'chore',
        'revert',
        'build',
      ],
    ],
    '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', 72],
  },
}

③在package.json中配置scripts命令

# 在scrips中添加下面的代码
{
   
"scripts": {
   
    "commitlint": "commitlint --config commitlint.config.cjs -e -V"
  },
}

commit信息需要带着下面的subject

配置结束,现在当我们填写commit信息的时候,前面就需要带着下面的subject

'feat',//新特性、新功能
'fix',//修改bug
'docs',//文档修改
'style',//代码格式修改, 注意不是 css 修改
'refactor',//代码重构
'perf',//优化相关,比如提升性能、体验
'test',//测试用例修改
'chore',//其他修改, 比如改变构建流程、或者增加依赖库、工具等
'revert',//回滚到上一个版本
'build',//编译相关的修改,例如发布版本、对项目构建或者依赖的改动

⑤配置husky

npx husky add .husky/commit-msg 

⑥在生成的commit-msg文件中添加下面的命令

#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
pnpm commitlint

当我们 commit 提交信息时,就不能再随意写了,必须是 git commit -m 'fix: xxx' 符合类型的才可以,需要注意的是类型的后面需要用英文的 :,并且冒号后面是需要空一格的,这个是不能省略的

示例

如下,不写feat那些就会报错的
在这里插入图片描述

1.3.8 强制使用pnpm包管理器工具

团队开发项目的时候,需要统一包管理器工具,因为不同包管理器工具下载同一个依赖,可能版本不一样,导致项目出现bug问题,因此包管理器工具需要统一管理!!!

①在根目录创建scritps/preinstall.js文件

添加下面的内容

if (!/pnpm/.test(process.env.npm_execpath || '')) {
   
  console.warn(
    `\u001b[33mThis repository must using pnpm as the package manager ` +
    ` for scripts to work properly.\u001b[39m\n`,
  )
  process.exit(1)
}

②配置命令

pakage.json里面添加命令

"scripts": {
	"preinstall": "node ./scripts/preinstall.js"
}

当我们使用npm或者yarn来安装包的时候,就会报错了。原理就是在install的时候会触发preinstall(npm提供的生命周期钩子)这个文件里面的代码。

示例:
我们使用yarn安装elementui-plus,就会报错;使用`pnpm``安装没有问题
在这里插入图片描述

相关推荐

  1. vue3项目企业级

    2024-01-30 14:54:02       16 阅读
  2. 前端Vue2项目过程

    2024-01-30 14:54:02       14 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-30 14:54:02       19 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-30 14:54:02       20 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-30 14:54:02       20 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-30 14:54:02       20 阅读

热门阅读

  1. udp(无连接)客户端和服务端代码

    2024-01-30 14:54:02       48 阅读
  2. 快捷键:IDEA 清理无效导入依赖

    2024-01-30 14:54:02       35 阅读
  3. STL之stack 【栈】

    2024-01-30 14:54:02       30 阅读
  4. VA_LIST可变参数列表使用学习

    2024-01-30 14:54:02       34 阅读
  5. 正则表达式 grep

    2024-01-30 14:54:02       32 阅读
  6. STM32 1-5

    STM32 1-5

    2024-01-30 14:54:02      34 阅读
  7. 【iOS ARKit】光照效果--光源

    2024-01-30 14:54:02       38 阅读
  8. C. Did We Get Everything Covered?

    2024-01-30 14:54:02       32 阅读
  9. k8s默认seccomp禁用研究

    2024-01-30 14:54:02       36 阅读