vite6+vue3+ts+prettier+eslint9配置前端项目(背景管理系统、移动端H5项目 ...

打印 上一主题 下一主题

主题 704|帖子 704|积分 2112

很多小伙伴苦于无法搭建一个规范的前端项目,导致后续开辟不规范,今天给各人带来一个基于Vite6+TypeScript+Vue3+ESlint9+Prettier的搭建教程。
  
  
环境依赖版本
   

  • node:v18.20.0
  • vite:^6.0.5
  • typescript:~5.6.2
  • vue:^3.5.13
  • eslint: ^9.14.0,
  • vite-plugin-checker: ^0.8.0"
  一、基础配置

   最新版vue官方已放弃webpack作为构建工具,vue官方之前一直是以webpack,但是近期我发现vue官网已经更新了相关内容,目前开始主推vite作为脚手架构建的工具,使用官方推荐的脚手架会更加方便,脚手架可自行选择ts、pinia 、router等相关配置,不用再像之前一样重新到尾举行安装,简朴又方便!!!
官方所在:https://cn.vuejs.org/guide/quick-start.html
  1、初始化项目

留意:此处使用node版本需要>18.3
  1. pnpm create vue@latest
复制代码
运行指令后接下来就是根据需要安装所需的功能

初始化完成的结构如图所示

2、代码质量风格的统一

   eslint可以包管项目的质量,prettier可以包管项目的统一格式、风格。
每个公司的开辟规则各有差别,此处根据各自的需求自行配置,下方是我常用的风格配置(仅供参考)
  2.1、配置prettier



  • 安装
eslint prettier插件安装、用来办理与eslint的辩论、安装prettier
  1. pnpm add eslint-plugin-prettier eslint-config-prettier prettier -D
复制代码


  • 新增.prettierrc.json文件

  1. {
  2.   "$schema": "https://json.schemastore.org/prettierrc",
  3.   "semi": true,
  4.   "tabWidth": 2,
  5.   "singleQuote": true,
  6.   "printWidth": 150,
  7.   "bracketSpacing": true,
  8.   "arrowParens": "always",
  9.   "endOfLine": "lf",
  10.   "trailingComma": "all",
  11.   "bracketSameLine": false,
  12.   "embeddedLanguageFormatting": "auto",
  13.   "useTabs": false,
  14.   "htmlWhitespaceSensitivity": "ignore"
  15. }
复制代码
2.2、配置eslint



  • 规则
   

  • “off” 或 0 - 关闭规则
  • “warn” 或 1 - 打开规则作为警告(不影响退出代码)
  • “error” 或 2 - 打开规则作为错误(触发时退出代码为 1)
  

  • 安装
  1. // eslint vue插件安装
  2. pnpm add eslint eslint-plugin-vue -D
  3. //eslint 识别ts语法
  4. pnpm add @typescript-eslint/parser
  5. //eslint ts默认规则补充
  6. pnpm add @typescript-eslint/eslint-plugin -D
复制代码
  自 ESLint v9.0.0 以后,平面配置文件格式一直是默认的配置文件格式。配置文件格式已从 eslintrc 更改为 flat config。默认环境下,ESLint CLI 将搜刮 eslint.config.(js | cjs | mjs) 而不是 .eslintrc.* 文件。假如未找到 eslint.config.js 文件,CLI 会将其视为错误,而且不会运行。
以下是官方给出的具体介绍。https://eslint.org/docs/latest/use/configure/migration-guide
可参考以下文章:
探索 Antfu ESLint 配置:一款极为便捷的 ESLint 设置方案
ESLint 扁平化配置使用指南
  

  • 修改eslint.config.js配置信息
  1. import pluginVue from 'eslint-plugin-vue';
  2. import typescriptEslint from '@typescript-eslint/eslint-plugin';
  3. import prettier from 'eslint-plugin-prettier';
  4. import vueTsEslintConfig from '@vue/eslint-config-typescript';
  5. import skipFormatting from '@vue/eslint-config-prettier/skip-formatting';
  6. import vueEslintParser from 'vue-eslint-parser';
  7. import tsEslintParser from '@typescript-eslint/parser';
  8. export default [
  9.   {
  10.     name: 'app/files-to-lint',
  11.     files: ['**/*.{ts,mts,tsx,vue,js,jsx}'],
  12.   },
  13.   {
  14.     name: 'app/files-to-ignore',
  15.     ignores: ['**/dist/**', '**/dist-ssr/**', '**/coverage/**', 'node_modules'],
  16.     // plugins: ['vue', '@typescript-eslint', 'prettier'],
  17.   },
  18.   ...pluginVue.configs['flat/essential'],
  19.   ...vueTsEslintConfig(),
  20.   skipFormatting,
  21.   {
  22.     name: 'app/plugins',
  23.     plugins: {
  24.       vue: pluginVue,
  25.       '@typescript-eslint': typescriptEslint,
  26.       prettier,
  27.     },
  28.   },
  29.   {
  30.     name: 'app/parser-config-vue',
  31.     languageOptions: {
  32.       parser: vueEslintParser,
  33.     },
  34.   },
  35.   {
  36.     name: 'app/parser-config-ts',
  37.     files: ['**/*.{ts,mts,tsx}'],
  38.     languageOptions: {
  39.       parser: tsEslintParser,
  40.       parserOptions: {
  41.         ecmaVersion: 'latest',
  42.         sourceType: 'module',
  43.         ecmaFeatures: {
  44.           jsx: true,
  45.         },
  46.       },
  47.     },
  48.   },
  49.   {
  50.     name: 'app/custom-rules',
  51.     rules: {
  52.       'no-console': process.env.NODE_ENV === 'production' ? 'off' : 'off',
  53.       'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
  54.       'key-spacing': [
  55.         'error',
  56.         {
  57.           beforeColon: false,
  58.           afterColon: true,
  59.         },
  60.       ],
  61.       'space-in-parens': ['error', 'never'],
  62.       'object-curly-spacing': ['error', 'always'],
  63.       'object-curly-newline': [
  64.         'error',
  65.         {
  66.           minProperties: 4,
  67.           multiline: true,
  68.           consistent: true,
  69.         },
  70.       ],
  71.       'vue/object-curly-spacing': ['error', 'always'],
  72.       'max-len': 'off',
  73.       'no-multi-spaces': 'error',
  74.       'no-return-assign': 'off',
  75.       semi: ['error', 'always'],
  76.       eqeqeq: 'error',
  77.       'jsx-quotes': ['off', 'prefer-single'],
  78.       'jsx-a11y/click-events-have-key-events': 'off',
  79.       'jsx-a11y/no-noninteractive-element-interactions': 'off',
  80.       'import/prefer-default-export': 'off',
  81.       'import/extensions': 'off',
  82.       'import/no-unresolved': 'off',
  83.       'no-multiple-empty-lines': [
  84.         'error',
  85.         {
  86.           max: 2,
  87.           maxEOF: 1,
  88.         },
  89.       ],
  90.       'no-param-reassign': 'off',
  91.       'vue/eqeqeq': ['error', 'always'],
  92.       'vue/html-end-tags': 'error',
  93.       'vue/no-spaces-around-equal-signs-in-attribute': 'error',
  94.       'vue/multi-word-component-names': 'off',
  95.       'vue/no-template-shadow': 'error',
  96.       'vue/require-prop-types': 'error',
  97.       'vue/require-explicit-emits': 'error',
  98.       'vue/mustache-interpolation-spacing': ['error', 'always'],
  99.       'vue/no-multi-spaces': [
  100.         'error',
  101.         {
  102.           ignoreProperties: false,
  103.         },
  104.       ],
  105.       'vue/html-closing-bracket-newline': [
  106.         'error',
  107.         {
  108.           singleline: 'never',
  109.           multiline: 'always',
  110.         },
  111.       ],
  112.       'vue/html-self-closing': 'off',
  113.       'vue/block-lang': 'off',
  114.       'vue/html-indent': [
  115.         'error',
  116.         2,
  117.         {
  118.           attribute: 1,
  119.           baseIndent: 1,
  120.           closeBracket: 0,
  121.           alignAttributesVertically: true,
  122.           ignores: ['VExpressionContainer'],
  123.         },
  124.       ],
  125.       'vue/html-closing-bracket-spacing': [
  126.         'error',
  127.         {
  128.           startTag: 'never',
  129.           endTag: 'never',
  130.           selfClosingTag: 'always',
  131.         },
  132.       ],
  133.       'vue/max-attributes-per-line': [
  134.         'error',
  135.         {
  136.           singleline: 3,
  137.           multiline: 1,
  138.         },
  139.       ],
  140.       'vue/attribute-hyphenation': 'off',
  141.       '@typescript-eslint/no-shadow': 'off',
  142.       '@typescript-eslint/no-explicit-any': 'off',
  143.       '@typescript-eslint/no-unused-vars': 'error',
  144.       '@typescript-eslint/ban-ts-comment': 'off',
  145.       '@typescript-eslint/indent': 'off',
  146.     },
  147.   },
  148. ];
复制代码
2.3、配置typescript



  • 修改配置tsconfig.json文件
  1. {
  2.   "extends": "@vue/tsconfig/tsconfig.dom.json",
  3.   "exclude": ["src/**/__tests__/*", "node_modules/**"],
  4.   "compilerOptions": {
  5.     "target": "ES2020",
  6.     "useDefineForClassFields": true,
  7.     "module": "ESNext",
  8.     "lib": ["ES2020", "DOM", "DOM.Iterable"],
  9.     "skipLibCheck": true,
  10.     /* Bundler mode */
  11.     "moduleResolution": "node",
  12.     "allowImportingTsExtensions": true,
  13.     "resolveJsonModule": true,
  14.     "isolatedModules": true,
  15.     "noEmit": true,
  16.     "jsx": "preserve",
  17.     "allowJs": true,
  18.     /* Linting */
  19.     "strict": true,
  20.     "noUnusedLocals": true,
  21.     "noUnusedParameters": true,
  22.     "noFallthroughCasesInSwitch": true,
  23.     /* Paths */
  24.     "baseUrl": ".",
  25.     "paths": {
  26.       "@/*": ["./src/*"]
  27.     }
  28.   },
  29.   "files": [],
  30.   "references": [
  31.     {
  32.       "path": "./tsconfig.node.json"
  33.     },
  34.     {
  35.       "path": "./tsconfig.app.json"
  36.     }
  37.   ]
  38. }
复制代码
3、配置代码检查器

vite-plugin-checker 是一个 Vite 插件,它能够在工作线程中运行 TypeScript、ESLint、vue-tsc、Stylelint 等多种静态代码检查工具,以提高开辟效率并确保代码质量。


  • 安装
  1. pnpm add vite-plugin-checker -D
复制代码


  • 修改vite.config.ts配置
  1. import { fileURLToPath, URL } from 'node:url';
  2. import { defineConfig } from 'vite';
  3. import vue from '@vitejs/plugin-vue';
  4. import vueJsx from '@vitejs/plugin-vue-jsx';
  5. import checker from 'vite-plugin-checker';
  6. import vueDevTools from 'vite-plugin-vue-devtools';
  7. // https://vite.dev/config/
  8. export default defineConfig({
  9.   base: './',    // 配置服务器的检索方式
  10.   plugins: [
  11.     vue(),
  12.     vueJsx(),
  13.     vueDevTools(),
  14.     checker({
  15.       eslint: {
  16.         useFlatConfig: true,
  17.         lintCommand: 'eslint "./src/**/*.{ts,tsx,vue}"',
  18.       },
  19.       overlay: {
  20.         initialIsOpen: false,
  21.       },
  22.       typescript: true,
  23.       vueTsc: true,
  24.     }),
  25.   ],
  26.   resolve: {
  27.     alias: {
  28.       '@': fileURLToPath(new URL('./src', import.meta.url)),
  29.     },
  30.   },
  31.   // 配置外部 ip 访问与端口
  32.   server: {
  33.     host: '0.0.0.0',
  34.     port: 9999,
  35.   },
  36. });
复制代码
4、修改路由配置信息

假如公司对应服务没有做相关的路由映射,需要将src/router/index.ts中的createWebHistory替换成createWebHashHistory,假如有请忽略这一步调~
如下所示

二、重置浏览器默认样式

normalize.css 是一个用于重置浏览器默认样式的库,使得差别浏览器之间的渲染更加一致


  • 安装
  1. pnpm add normalize.css
复制代码


  • src/mian.ts引入
  1. import './assets/main.css';
  2. import { createApp } from 'vue';
  3. import { createPinia } from 'pinia';
  4. import App from './App.vue';
  5. import router from './router';
  6. import 'normalize.css';
  7. const app = createApp(App);
  8. app.use(createPinia());
  9. app.use(router);
  10. app.mount('#app');
复制代码
三、安装样式预处理器

各人可以自行安装自己熟悉的预处理器(less、sass、stylus……),此处我选择自己常用的sass
  1. pnpm add sass -D
复制代码
tip:vite内置了常用的预处理器支持无需,安装配置sass-loader 即可使用
四、ui组件库安装

市面上的ui组件库有很多,此处我只提供我最常用的两种组件库举行配置
   假如是搭建背景管理系统,此处可看element-plus配置。
假如是搭建移动端h5,此处发起可看vant组件库
  1、element-plus组件库配置

官方文档配置:https://element-plus.org/zh-CN/guide/quickstart.html


  • 安装
  1. pnpm add element-plus
  2. pnpm add -D unplugin-vue-components unplugin-auto-import
复制代码


  • 修改vite.config.ts配置
  1. import { fileURLToPath, URL } from 'node:url';
  2. import { defineConfig } from 'vite';
  3. import vue from '@vitejs/plugin-vue';
  4. import vueJsx from '@vitejs/plugin-vue-jsx';
  5. import checker from 'vite-plugin-checker';
  6. import vueDevTools from 'vite-plugin-vue-devtools';
  7. import AutoImport from 'unplugin-auto-import/vite';
  8. import Components from 'unplugin-vue-components/vite';
  9. import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';
  10. // https://vite.dev/config/
  11. export default defineConfig({
  12.   base: './', // 设置打包路径
  13.   plugins: [
  14.     vue(),
  15.     vueJsx(),
  16.     vueDevTools(),
  17.     AutoImport({
  18.       resolvers: [ElementPlusResolver()],
  19.     }),
  20.     Components({
  21.       resolvers: [ElementPlusResolver()],
  22.     }),
  23.     checker({
  24.       eslint: {
  25.         useFlatConfig: true,
  26.         lintCommand: 'eslint "./src/**/*.{ts,tsx,vue}"',
  27.       },
  28.       overlay: {
  29.         initialIsOpen: false,
  30.       },
  31.       typescript: true,
  32.       vueTsc: true,
  33.     }),
  34.   ],
  35.   resolve: {
  36.     alias: {
  37.       '@': fileURLToPath(new URL('./src', import.meta.url)),
  38.     },
  39.   },
  40.   server: {
  41.     host: '0.0.0.0',
  42.     port: 9999,
  43.   },
  44. });
复制代码
2、vant组件库配置

官方文档配置: https://vant-ui.github.io/vant/#/zh-CN/quickstart


  • 安装
  1. pnpm add vant
  2. pnpm add @vant/auto-import-resolver unplugin-vue-components unplugin-auto-import -D
复制代码


  • 修改vite.config.ts配置
  1. import { fileURLToPath, URL } from 'node:url';
  2. import { defineConfig } from 'vite';
  3. import vue from '@vitejs/plugin-vue';
  4. import vueJsx from '@vitejs/plugin-vue-jsx';
  5. import checker from 'vite-plugin-checker';
  6. import vueDevTools from 'vite-plugin-vue-devtools';
  7. import AutoImport from 'unplugin-auto-import/vite';
  8. import Components from 'unplugin-vue-components/vite';
  9. import { VantResolver } from '@vant/auto-import-resolver';
  10. // https://vite.dev/config/
  11. export default defineConfig({
  12.   base: './', // 设置打包路径
  13.   plugins: [
  14.     vue(),
  15.     vueJsx(),
  16.     vueDevTools(),
  17.     AutoImport({
  18.       resolvers: [VantResolver()],
  19.     }),
  20.     Components({
  21.       resolvers: [VantResolver()],
  22.     }),
  23.     checker({
  24.       eslint: {
  25.         useFlatConfig: true,
  26.         lintCommand: 'eslint "./src/**/*.{ts,tsx,vue}"',
  27.       },
  28.       overlay: {
  29.         initialIsOpen: false,
  30.       },
  31.       typescript: true,
  32.       vueTsc: true,
  33.     }),
  34.   ],
  35.   resolve: {
  36.     alias: {
  37.       '@': fileURLToPath(new URL('./src', import.meta.url)),
  38.     },
  39.   },
  40.   server: {
  41.     host: '0.0.0.0',
  42.     port: 9999,
  43.   },
  44. });
复制代码
五、二次封装axios



  • 安装
  1. pnpm add axios
复制代码
新增src/service/index.ts文件
  1. import Axios from 'axios';
  2. import type { AxiosInstance, InternalAxiosRequestConfig, AxiosResponse } from 'axios';
  3. const axios: AxiosInstance = Axios.create({
  4.   baseURL: 'XXX',
  5.   timeout: 20000,
  6.   withCredentials: true,
  7. });
  8. axios.interceptors.request.use(
  9.   (config: InternalAxiosRequestConfig) => {
  10.     return config;
  11.   },
  12.   (error) => {
  13.     // pendingRequest.clear();
  14.     console.log(error);
  15.     return Promise.reject(error);
  16.   },
  17. );
  18. // 请求结束关闭loading
  19. axios.interceptors.response.use(
  20.   (response: AxiosResponse) => {
  21.     // console.log(response);
  22.     return response.data || {};
  23.   },
  24.   (err) => {
  25.     console.log('err', err);
  26.     return Promise.reject(err);
  27.   },
  28. );
  29. export function get<T>(url: string, params?: any): Promise<T> {
  30.   return axios.get(url, { params });
  31. }
  32. export function post<T>(url: string, data?: any): Promise<T> {
  33.   return axios.post(url, data);
  34. }
  35. export default axios;
复制代码
六、配置环境变量

1、创建配置文件

根目录创建三个配置文件,更多环境一样云云操作。
注: 界说的变量必须以VITE_开头


  • .env.development (开辟环境)
  1. VITE_APP_ENV = 'development';
  2. VITE_APP_API_URL = /api / xxx务后地服本端 / xxx测试 / xxx生产都行;
复制代码


  • .env.test (测试环境)
  1. VITE_APP_ENV = 'test';
  2. VITE_APP_API_URL = xxx测试域名;
复制代码


  • .env.production (生产环境)
  1. VITE_APP_ENV = 'production';
  2. VITE_APP_API_URL = xxx生产域名;
复制代码
2、使用变量



  • 在代码中使用
  1. const baseUrl = import.meta.env.VITE_BASE_URL;
复制代码


  • 在vite.config.ts中使用环境变量
  1. // 使用loadEnv方法加载环境变量
  2. import { defineConfig, loadEnv } from 'vite';
  3. //...
  4. export default ({ mode }) => {
  5.   console.log('加载的环境变量', loadEnv(mode, process.cwd()).VITE_BASE_URL);
  6.   return defineConfig({
  7.     //...
  8.   });
  9. };
复制代码
3、修改package.json启动下令

  1.   "scripts": {
  2.     "dev": "vite --mode development",
  3.     "build": "vite build --mode production",
  4.   },
复制代码
七、拓展实用插件(按需安装配置)

   此处推荐一些我常用的工具库,各人可以参考按需安装。相关使用方法网上一搜一大堆,这边就不多余再演示了
  1、dayjs 时间处理

Day.js是一个极简的JavaScript库, 可以为现代浏览器解析、验证、操作和显示日期和时间,文件巨细只有2KB左右。Day.js对国际化有很大的支持。
  1. pnpm add dayjs
复制代码
2、qs

qs是一个流行的查询参数序列化和解析库。
  1. pnpm add qs
  2. // 如果项目配置了typescript需安装
  3. pnpm add @types/qs -D
复制代码
3、lodash实用工具库

Lodash 是一个一致性、模块化、高性能的 JavaScript 实用工具库。它提供了一套从数组、数字、对象、字符串、日期等常见数据类型中提取值的函数,以及很多其他实勤奋能。Lodash 旨在通过提高抽象程度来减少代码量,提高代码的可维护性。
  1. pnpm add lodash
  2. // 如果项目配置了typescript需安装
  3. pnpm add @types/lodash -D
复制代码
4、big.js(涉及计算相关)

big.js 是一个用于任意精度十进制算术的小型快速 JavaScript 库。 它允许你创建、操作和比较大数字,这些数字的精度凌驾了 JavaScript 原生 Number 类型所能提供的范围。主要可以用于处理需要高精度计算的场景,例如金额计算、科学计算、密码学等等。
  1. pnpm add big.js
  2. // 如果项目配置了typescript需安装
  3. pnpm add @types/big.js -D
复制代码
5、js-cookie

是一个简朴、轻量级的 JavaScript API 库,用于处理浏览器 cookies。它允许你创建、读取、删除和操作 cookie,而不需要担心浏览器的兼容性问题。
  1. pnpm add js-cookie
  2. // 如果项目配置了typescript需安装
  3. pnpm add @types/js-cookie -D
复制代码
6、postcss-plugin-px2rem

postcss-plugin-px2rem 是一个 PostCSS 插件,它可以主动 将 CSS 文件中的像素单位(px)转换为相对单位(rem),以实现响应式结构和移动端适配。这个插件特殊适用于需要根据差别分辨率的移动设备举行适配的场景。


  • 安装
  1. pnpm add -D postcss-plugin-px2rem autoprefixer
复制代码


  • 配置vite.config.js
  1. import autoprefixer from 'autoprefixer'
  2. import postcssPluginPx2rem from 'postcss-plugin-px2rem';
  3. import { defineConfig } from 'vite';
  4. // https://vitejs.dev/config/
  5. export default defineConfig({
  6.   plugins: [
  7.   ...
  8.   ],
  9.   resolve: {
  10.   ...
  11.   },
  12.   css: {
  13.     postcss: {
  14.       plugins: [
  15.         autoprefixer,
  16.         postcssPluginPx2rem({
  17.           remUnit: 108,
  18.           rootValue: 108, // 换算基数,1rem 相当于多少 px
  19.                   unitPrecision: 5, // 允许 REM 单位增长到的十进制数字
  20.                   propWhiteList: [], // 白名单,指定哪些属性不转换为 rem
  21.                   propBlackList: [], // 黑名单,指定哪些属性需要转换为 rem
  22.                   exclude: /(node_module)/, // 排除的文件夹或文件
  23.                   selectorBlackList: [], // 要忽略并保留为 px 的选择器
  24.                   mediaQuery: false, // 允许在媒体查询中转换 px
  25.                   minPixelValue: 3 // 设置要替换的最小像素值
  26.         }),
  27.       ],
  28.     },
  29.   },
  30. });
复制代码
7、@vitejs/plugin-legacy(兼容旧浏览器,移动端项目重点推荐!!!)

   公司合作的一些客户自带的客户端浏览器版本超级无敌老旧(此处内涵某些银行

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

张裕

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表