vue3.2 + vite + ts + vue-router4 + pinia + elementPlus + echarts5 项目搭建及初始化(一)

168 阅读6分钟

vue3.2 + vite + ts + vue-router4 + pinia + elementPlus + echarts5 项目初始化 (代序)

一.项目搭建

全局安装pnpm,安装命令为

注意: 安装 pnpm, node 的版本号要大于 V14.19.0

npm i pnpm -g

在VScode里面下载插件Vue Language Features(Volar),禁用掉 Vetur,不然代码会报一堆错误

接下来,我们开始构建项目

1.在需要创建项目文件目录下打开 cmd 运行下列命令

pnpm create vite

2.输入项目名称

? Project name: » vue3-ts-elementPlus-pinia-echarts

3.选择一个框架

? Select a framework: » - Use arrow-keys. Return to submit.
    Vanilla
>   Vue
    React
    Preact
    Lit
    Svelte
    Others

4.选择使用 TypeScript

? Select a variant: » - Use arrow-keys. Return to submit.
    JavaScript
>   TypeScript
    Customize with create-vue ↗
    Nuxt ↗

5.找到文件夹,用 vscode 打开,首先使用 pnpm i 安装依赖, 在使用命令 pnpm dev就可以启动项目了

这里注意: 如果安装依赖时出错,可以切换淘宝远

pnpm config set registry https://registry.npmmirror.com/

项目启动成功,打开之后,可以看到如下所示

二.设置并约束代码风格

往往我们写代码的时候,最讨厌的是地下大部分的红色报错信息,并且格式错乱,所以可以配置一些相关信息,完善我们的代码风格

配置 eslintprettier

1.执行下列命令安装依赖

pnpm i eslint -D 
pnpm i prettier -D
pnpm i eslint-plugin-vue -D
pnpm i eslint-plugin-prettier -D
pnpm i eslint-config-prettier -D
pnpm i @typescript-eslint/eslint-plugin -D
pnpm i @typescript-eslint/parser -D
pnpm i @vue/eslint-config-prettier -D
pnpm i @vue/eslint-config-typescript -D

2.项目下新建 .eslintrc.js 文件,并配置 eslint 的检验规则

module.exports = {
  // ESLint 一旦发现配置文件中有 "root": true,它就会停止在父级目录中寻找。
  root: true,
  // 指定脚本的运行环境。每种环境都有一组特定的预定义全局变量。
  env: {
    browser: true,
    es6: true,
    node: true,
    'vue/setup-compiler-macros': true
  },
  // 指定如何解析语法
  parser: 'vue-eslint-parser',
  // 优先级低于parse的语法解析配置
  parserOptions: {
    // js的版本
    ecmaVersion: 2020,
    // 解析器
    parser: '@typescript-eslint/parser',
    // 模块化方案
    sourceType: 'module',
    ecmaFeatures: {
      jsx: true
    }
  },
  // plugins: ['@typescript-eslint'], //定义了该eslint文件所依赖的插件
​
  // 代表你启动哪些 lint 选项,如果多个规则直接有冲突的话,extends后面的选项会覆盖前面的。
  extends: [
    // 'eslint:recommended',
    // 防止错误或意外行为的规则
    'plugin:vue/vue3-essential',
    // 大大提高代码可读性和/或开发体验的规则
    'plugin:vue/vue3-strongly-recommended',
    // 加上强制执行主观社区默认值的规则,以确保一致性
    'plugin:vue/vue3-recommended',
    //  typescript-eslint推荐规则
    'plugin:@typescript-eslint/recommended',
​
    'prettier',
    // 使用prettier中的样式规范,且如果使得ESLint会检测prettier的格式问题,同样将格式问题以error的形式抛出
    'plugin:prettier/recommended'
  ],
  rules: {
    // override/add rules settings here, such as:
    // 禁止不必要的分号
    // '@typescript-eslint/no-extra-semi': 'off',
    // 如不禁用这条规则会导致命名为index或其他单字母组件名的文件报错,(不要求组件名称始终为多字)
    'vue/multi-word-component-names': 0,
    // 允许属性之间使用驼峰命名,不强制要求使用 - 连字符
    'vue/attribute-hyphenation': 0,
    // 不需要 props 的默认值
    'vue/require-default-prop': 'off',
    // 禁止 v-for 指令或范围属性的未使用变量定义
    '@typescript-eslint/no-unused-vars': [
      'error',
      {
        argsIgnorePattern: '^_',
        varsIgnorePattern: '^_'
      }
    ],
    'no-unused-vars': [
      'error',
      {
        argsIgnorePattern: '^_',
        varsIgnorePattern: '^_'
      }
    ],
    '@typescript-eslint/no-non-null-assertion': 'off',
    '@typescript-eslint/no-explicit-any': 'off'
  }
}
​

自定义规则,具体配置可参考:eslint.vuejs.org/rules/

3.在项目下新建 .eslintignore 文件,配置 eslint 忽略检查的文件或目录

dist/
es/
lib/
node_modules/
.gitignore
*.sh
*.md
*.woff
*.ttf
.vscode
.idea
/public
/docs
.husky
.local
/bin
Dockerfile

4.项目下新建 .prettierrc.js 文件,配置 prettier 代码风格

module.exports = {
  // 使用 2 个空格缩进
  tabWidth: 2,
  // 不使用 tab 缩进,而使用空格
  useTabs: false,
  // 行尾不需要分号
  semi: false,
  // // jsx 标签的反尖括号需要换行
  // jsxBracketSameLine: false,
  // // jsx 不使用单引号,而使用双引号
  // jsxSingleQuote: false,
  // 箭头函数,只有一个参数的时候,不需要括号
  arrowParens: 'avoid',
  // 使用单引号代替双引号
  singleQuote: true,
  // 在对象,数组括号与文字之间加空格 "{ foo: bar }"
  bracketSpacing: true,
  // 换行符使用 lf
  endOfLine: 'lf',
  // 末尾不使用逗号
  trailingComma: 'none',
  // 使用默认的折行标准
  proseWrap: 'preserve'
  // 根据显示样式决定 html 要不要折行
  // htmlWhitespaceSensitivity: 'css'
}

更多配置信息,可参考官网:www.prettier.cn/docs/index.…

这里有个细节,如果vite的版本大于3的话,文件的后缀名改为cjs 并且重新打开编辑器

5.项目下新建 .prettierignore ,配置 prettier 忽略文件

dist/
es/
lib/
node_modules/
​
pnpm-lock.yaml
pnpm-workspace.yaml
​
CHANGELOG.md
​
.local
.output.js
**/*.svg
**/*.sh
/public/*
​

6.package.json 文件下添加以下配置

 "scripts": {
    "eslint:comment": "使用 ESLint 检查并自动修复 src 目录下所有扩展名为 .js 和 .vue 的文件",
    "eslint": "eslint --ext .tsx,.ts,.js,.vue --ignore-path .gitignore --fix src",
    "prettier:comment": "自动格式化当前目录下的所有文件",
    "prettier": "prettier --write"
  },

配置编辑器风格

1.项目下 .vscode 文件夹下新增两个文件 extensions.jsonsettings.json, 并配置以下信息

extensions,json

{
  "recommendations": [
    "Vue.volar",
    "EditorConfig.EditorConfig",
    "esbenp.prettier-vscode",
    "dbaeumer.vscode-eslint",
    "streetsidesoftware.code-spell-checker",
    "jaskang.vsc-commitizen"
  ]
}

settings.json

{
  "editor.tabSize": 2,
  "editor.wordWrap": "on",
  // #每次保存的时候自动格式化
  "editor.formatOnSave": true,
  // #每次保存的时候将代码按eslint格式进行修复
  "eslint.codeActionsOnSave": {
    "source.fixAll.eslint": true
  },
  // #去掉代码结尾的分号
  "prettier.semi": false,
  // #使用单引号替代双引号
  "prettier.singleQuote": true,
  // #让函数(名)和后面的括号之间加个空格
  "javascript.format.insertSpaceBeforeFunctionParenthesis": false,
  //  设置默认序列换行符为lf
  "files.eol": "\n",
  "vue3snippets.enable-compile-vue-file-on-did-save-code": false
}
​

2.在项目下新建 .editorconfig 文件,配置以下信息

root = true# 匹配全部文件
[*]# 设置字符集
charset = utf-8# 末尾行去掉尾随的空格
trim_trailing_whitespace = true# 末尾行后加多一行空行
insert_final_newline = true# <"tab" | "space"> 制表符类型
indent_style = space
indent_size = 2# <"lf" | "cr" | "crlf"> 换行符类型
end_of_line = lf

更多配置信息,可参考官网:editorconfig.org

配置文件引用别名

vite.config.ts 下配置以下信息:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src')
    }
  }
})
​

修改配置 tsconfig.json 文件

{
  "compilerOptions": {
    // 使用的es版本  esnext表示最高
    "target": "esnext",
    "useDefineForClassFields": true,
    // tsc编译后的规范文件
    "module": "esnext",
    // 是否允许引入js文件
    "allowJs": true,
    // 编译的模块化的方案
    "moduleResolution": "node",
    // 是否采用严格模式
    "strict": true,
    // 限制对空值的检查
    "strictNullChecks": false,
    // jsx代码编译后的规范
    "jsx": "preserve",
    // 生成编译前代码的映射文件
    "sourceMap": true,
    "resolveJsonModule": true,
    // 将每个文件作为单独的模块
    "isolatedModules": true,
    // 允许ts文件中,同时引入 es和commonJS规范的文件
    "esModuleInterop": true,
    // 编译过程中需要引入的库文件的列表。
    "lib": ["esnext", "dom"],
    // 跳过声明文件的类型检查
    "skipLibCheck": true,
    // 开始查找ts文件的基础目录
    "baseUrl": "./",
    // 路径别名,通过某个标识符指定特定的目录
    "paths": {
      "@": ["src"],
      "@/*": ["src/*"]
    }
  },
  "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"],
  "references": [{ "path": "./tsconfig.node.json" }],
  // ts编译和检查排除的文件或者文件夹
  "exclude": ["node_modules", "dist", "**/*.js"]
}

至此,我们的代码风格及约束文件已经配置完毕,在之后的代码编辑中,能及时纠正格式错误,使代码书写更加规范,整洁,如有缺失遗漏的部分,望大家积极评论.

接下: juejin.cn/post/717433…