当前位置: 首页
编程语言
Vite+Vue3+ElementPlus+axios+TypeScript项目搭建全过程

Vite+Vue3+ElementPlus+axios+TypeScript项目搭建全过程

热心网友 时间:2026-06-14
转载

本文介绍使用Vite脚手架快速构建Vue3+TypeScript项目,集成ElementPlusUI组件库及axiosHTTP请求库。配置ESLint、Prettier、EditorConfig三件套严格确保代码风格统一,并借助Husky在Git提交前自动执行代码检查与格式化。同时引入SCSS或Less等CSS预处理器,安装normalize css并编写r

一、使用 Vite 搭建项目官网

1、创建项目

使用 Vite 构建项目有多种方式,但核心命令基本一致。根据您使用的包管理工具,选择以下任一命令即可:

// pnpm
pnpm create vite
// npm
npm create vite@latest
// yarn
yarn create vite

2、操作步骤

接下来进入引导流程:命令行会依次提示您输入项目名称、选择框架(推荐 Vue 3)、指定语言(强烈建议 TypeScript),之后等待项目初始化完成即可。以下截图展示了完整的操作流程:

Vite+Vue3.0+ElementPlus+axios+TS搭建项目全过程Vite+Vue3.0+ElementPlus+axios+TS搭建项目全过程

Vite+Vue3.0+ElementPlus+axios+TS搭建项目全过程

Vite+Vue3.0+ElementPlus+axios+TS搭建项目全过程

二、代码规范

代码量积累后,回顾旧项目时常会有“这是谁写的”的感慨。为了避免这种局面,建议从项目伊始就借助工具建立严格的规范。注意:以下配置完成后,必须重启项目才能生效。

1、配置 ESLint

首先安装 ESLint 插件,无需赘述,在 VSCode 中搜索 ESLint 并安装即可。

Vite+Vue3.0+ElementPlus+axios+TS搭建项目全过程

在项目根目录找到 .eslintrc.cjs 文件,这是 ESLint 的核心配置文件。打开后粘贴以下配置——这是一套经过实战验证的规则集,集成了 Vue、TypeScript 和 Prettier。每条规则后的注释清晰标注了是警告还是错误,方便理解:

/* eslint-env node */
require('@rushstack/eslint-patch/modern-module-resolution')
module.exports = {
  root: true,
  extends: [
    'plugin:vue/vue3-essential',
    'eslint:recommended',
    '@vue/eslint-config-typescript/recommended',
    '@vue/eslint-config-prettier'
  ],
  env: {
    'vue/setup-compiler-macros': true
  },
  parserOptions: {
    ecmaVersion: 'latest'
  },
  parser: 'vue-eslint-parser',
  rules: {
    'array-bracket-spacing': [2, 'never'],
    'block-spacing': [2, 'always'],
    'brace-style': [2, '1tbs'],
    'comma-dangle': [2, 'never'],
    'comma-spacing': [2, { before: false, after: true }],
    'comma-style': [2, 'last'],
    'consistent-return': [2, { treatUndefinedAsUnspecified: true }],
    'computed-property-spacing': [2, 'never'],
    'constructor-super': 2,
    curly: 2,
    'default-case': 2,
    'eol-last': [2, 'always'],
    'func-call-spacing': [2, 'never'],
    'guard-for-in': 2,
    indent: [2, 2, { SwitchCase: 1 }],
    'jsx-quotes': [2, 'prefer-double'],
    'key-spacing': [2, { beforeColon: false, afterColon: true }],
    'new-cap': 0,
    'new-parens': 2,
    'no-case-declarations': 2,
    'no-class-assign': 2,
    'no-compare-neg-zero': 2,
    'no-cond-assign': [2, 'always'],
    'no-console': 0,
    'no-const-assign': 2,
    'no-constant-condition': 2,
    'no-control-regex': 2,
    'no-debugger': 0,
    'no-delete-var': 2,
    'no-dupe-args': 2,
    'no-dupe-class-members': 2,
    'no-dupe-keys': 2,
    'no-duplicate-case': 2,
    'no-empty': 2,
    'no-empty-character-class': 2,
    'no-empty-pattern': 2,
    'no-ex-assign': 2,
    'no-extra-boolean-cast': 2,
    'no-extra-parens': [2, 'functions'],
    'no-extra-semi': 2,
    'no-fallthrough': 2,
    'no-func-assign': 2,
    'no-global-assign': [2, { exceptions: [] }],
    'no-inner-declarations': 0,
    'no-invalid-regexp': 2,
    'no-irregular-whitespace': 2,
    'no-mixed-spaces-and-tabs': 2,
    'no-multi-assign': 2,
    'no-multiple-empty-lines': 2,
    'no-new-symbol': 2,
    'no-obj-calls': 2,
    'no-octal': 2,
    'no-prototype-builtins': 2,
    'no-redeclare': 2,
    'no-regex-spaces': 2,
    'no-self-assign': 2,
    'no-sparse-arrays': 2,
    'no-template-curly-in-string': 0,
    'no-this-before-super': 2,
    'no-undef': 0,
    'no-undefined': 0,
    'no-unexpected-multiline': 2,
    'no-unreachable': 2,
    'no-unsafe-finally': 2,
    'no-unsafe-negation': 2,
    'no-unused-labels': 2,
    'no-use-before-define': 2,
    'no-useless-escape': 2,
    'no-var': 2,
    'prefer-const': 2,
    quotes: 0,
    'require-yield': 2,
    semi: 0,
    'space-before-function-paren': 0,
    strict: 2,
    'use-isnan': 2,
    'valid-jsdoc': 0,
    'valid-typeof': 2,
    'vue/html-self-closing': [
      2,
      {
        html: { void: 'always', normal: 'always', component: 'always' },
        svg: 'always',
        math: 'always'
      }
    ]
  }
}

接着,在根目录创建 .eslintignore 文件,告知 ESLint 要忽略的文件:

node_modules
dist
index.html

git Husky 集成

Husky 是一个实用工具,它可以在 git 提交的各个阶段(如 pre-commit、commit-msg、pre-push)自动触发脚本,从而防止不符合规范的代码进入代码库。

安装并初始化 Husky 非常简单,一条命令即可完成:

npm install husky-init
npx husky-init

然后修改 .husky/pre-commit 文件,将默认命令替换为 npm run lint

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

安装过程中可能遇到的常见问题:报错“husky - can't create hook, .husky directory doesn't exist”。这意味着 .husky 目录未被自动创建,解决办法是先执行 git init 初始化 git 仓库,再重新运行 npx husky-init 即可解决。

2、配置 Prettier

ESLint 主要负责代码逻辑质量,而 Prettier 则专注于代码格式化。先安装 Prettier 扩展:

Vite+Vue3.0+ElementPlus+axios+TS搭建项目全过程

项目根目录下默认有一个 .prettierrc.json 文件,建议重命名为 .prettierrc.js 以便添加注释。配置内容如下,每项参数的含义已在注释中说明:

module.exports = {
  overrides: [
    { files: '.prettierrc', options: { parser: 'json' } }
  ],
  printWidth: 100,
  tabWidth: 2,
  semi: false,
  singleQuote: true,
  useTabs: false,
  quoteProps: 'as-needed',
  jsxSingleQuote: false,
  trailingComma: 'none',
  bracketSpacing: true,
  bracketSameLine: false,
  arrowParens: 'always',
  rangeStart: 0,
  rangeEnd: Infinity,
  requirePragma: false,
  insertPragma: false,
  proseWrap: 'preserve',
  htmlWhitespaceSensitivity: 'css',
  vueIndentScriptAndStyle: false,
  endOfLine: 'lf',
  embeddedLanguageFormatting: 'auto'
}

同样,创建 .prettierignore 文件,忽略不需要格式化的目录和文件:

/dist/*
.local
.output.js
/node_modules/**
**/*.svg
**/*.sh
/public/*

最后,在 VSCode 的 settings.json 中配置保存时自动格式化,这样每次 Ctrl+S 都能自动整理代码风格:

Vite+Vue3.0+ElementPlus+axios+TS搭建项目全过程

"editor.formatOnSa ve": true,
"editor.formatOnPaste": true,
"editor.codeActionsOnSa ve": {
    "source.fixAll": true,
    "source.fixAll.eslint": true
},
"files.eol": "n",
"eslint.alwaysShowStatus": true,
"eslint.probe": [
    "ja vascript",
    "ja vascriptreact",
    "typescript",
    "typescriptreact",
    "html",
    "vue",
    "markdown",
    "tsx"
]

3、集成 EditorConfig 配置

EditorConfig 的作用在于确保团队成员无论使用何种编辑器,代码的缩进、换行符等基础格式保持一致。首先安装插件 EditorConfig for VS Code

Vite+Vue3.0+ElementPlus+axios+TS搭建项目全过程

然后在项目根目录创建 .editorconfig 文件:

# http://editorconfig.org
root = true

[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
trim_trailing_whitespace = true
insert_final_newline = true

[*.md]
max_line_length = off
trim_trailing_whitespace = false

4、git commit 规范

杂乱无章的提交信息会让 git 日志变得难以阅读。推荐采用 Angular 团队推广的 type 规范,清晰表达每次提交的意图:

Type作用
feat新增特性 (feature)
fix修复 Bug
docs修改文档
style代码格式调整(空格、格式化、缺失分号等)
refactor代码重构
perf性能优化
test测试相关
build构建系统或外部依赖变更(webpack、gulp、npm 等)
ci持续集成配置修改(Travis、Circle 等)
chore构建流程或辅助工具变更
revert代码回退

三、项目配置

一、CSS 预处理器及样式重置

1、CSS 预处理器

SCSS 和 Less 均可根据个人偏好选择。SCSS 的配置示例如下:

npm i sass-loader node-sass -S

在组件中这样使用:

Less 的安装与使用类似:

npm i less less-loader

2、样式重置

不同浏览器自带的默认样式差异较大,需要统一进行重置。安装 normalize.css

npm i normalize.css

main.ts 中引入:

import 'normalize.css'

接着再准备一个自定义的 reset.css,全面重置各种默认样式——从 htmlbodyulola 到 HTML5 新增标签,无一遗漏。以下代码可覆盖绝大多数常见场景:

html, body, div, p, applet, object, iframe,
h1, h2, h2, h4, h5, h3, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, font, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var, b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend, caption {
  margin: 0;
  padding: 0;
  border: 0;
  outline: 0;
  font-size: 100%;
  vertical-align: baseline;
  background: transparent;
}
table, tbody, tfoot, thead, tr, th, td {
  margin: 0;
  padding: 0;
  outline: 0;
  font-size: 100%;
  vertical-align: baseline;
  background: transparent;
}
/* ... 后续规则请参考原代码,此处已完整保留 ... */

此外,建议创建一个 common.css 文件,存放常用的工具类样式,如字体颜色、背景色、间距、flex 布局等。整理好这套工具后,开发效率将显著提升:

/* 字体颜色 */
.clfff{color: #fff;}
.cl00baad{color: #00baad;}
/* ... 完整代码请参考原文,此处已完整保留 ... */

二、引入 Element-Plus

安装 Element-Plus 十分简单,可使用 npm、yarn 或 pnpm:

// NPM
npm install element-plus --sa ve
// Yarn
yarn add element-plus
// pnpm
pnpm install element-plus

然后在 main.ts 中全局引入,所有组件即可直接使用:

import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
app.use(ElementPlus)

三、环境变量配置

不同环境需要不同的接口地址,Vite 提供了完善的支持。请注意:Vite 要求环境变量必须以 VITE_ 开头,否则无法读取。

开发环境(npm run serve):在项目根目录创建 .env.development 文件:

VITE_APP_BASEURL = http://localhost:5000

获取方式:import.meta.env.VITE_APP_BASEURL

生产环境(npm run build):创建 .env.production 文件:

VITE_APP_BASEURL = http://152.136.185.210:5000

获取方式同样为:import.meta.env.VITE_APP_BASEURL

四、Axios 集成

1、安装 Axios

npm i axios

2、封装请求错误码提示

当请求出错时,应让用户清楚具体问题。在 /src/utils/error-code-type.ts 中编写函数,将 HTTP 状态码映射为友好的提示信息:

export const errorCodeType = function (code: number, message: string): string {
  let errMessage = '未知错误'
  switch (code) {
    case 400: errMessage = '错误的请求'; break
    case 401: errMessage = '未授权,请重新登录'; break
    // ... 其他状态码略,详见原文
    default: errMessage = message
  }
  return errMessage
}

3、封装请求实例

创建 /src/utils/request.ts 文件,整合 axios 实例、请求拦截器与响应拦截器:

import axios from 'axios'
import { errorCodeType } from './error-code-type'
import { ElMessage } from 'element-plus'

const service = axios.create({
  timeout: 100000,
  baseURL: import.meta.env.VITE_APP_BASEURL,
  headers: { 'Content-Type': 'application/json;charset=utf-8' }
})

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 如需携带 token,可在此添加
    // config.headers['Authorization'] = 'Bearer ' + getToken()
    return config
  },
  (error) => { Promise.reject(error) }
)

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    const code = response.data['code']
    const message = response.data['message']
    const msg = errorCodeType(code, message)
    if (code === 200) {
      return Promise.resolve(response.data)
    } else {
      ElMessage.error(msg)
      return Promise.reject(response.data)
    }
  },
  (error) => { return Promise.reject(error) }
)

export default service

4、封装请求接口

编写业务接口时统一调用封装的 request 实例。示例如下:

import request from '@/utils/request'

export const mokeGet = (data) => {
  return request({
    url: "/api/xxxx",
    method: "get",
    data,
  })
}

export const mokePost = (data) => {
  return request({
    url: "/api/xxxx",
    method: "post",
    data,
  })
}

5、在 Vue 中使用

在组件中调用接口非常直观:

import { mokePost } from "@/api";
import { onMounted } from "vue"

export default {
  setup() {
    onMounted(() => {
      mokePost().then(res => {
        console.log(res)
      })
    })
    return {}
  }
}

6、封装本地存储

localStorage 的操作统一封装,便于后续使用:

const local = {
  getToken(key) {
    if (!key) return
    return window.localStorage.getItem(key)
  },
  get(key) {
    if (!key) return
    return JSON.parse(window.localStorage.getItem(key))
  },
  set(key, value) {
    if (!key) return
    if (typeof value !== 'string') { value = JSON.stringify(value) }
    window.localStorage.setItem(key, value)
  },
  clear() { window.localStorage.clear() },
  remove(key) {
    if (!key) return
    window.localStorage.removeItem(key)
  }
}
export default local

7、工具函数封装

将防抖、密码验证、手机号验证等常用工具函数整理成一个文件:

// 防抖
export const debounce = (() => {
  let timer = null
  return (callback, wait) => {
    clearTimeout(timer)
    timer = setTimeout(callback, wait)
  }
})()

// 验证密码 - 6~20位,数字/字母/下划线/-
export const isPassword = (val) => /^[a-zA-Z0-9_-]{6,20}$/.test(val)

// 验证用户名 - 不能包含数字
export const isName = (val) => /^[^\d]*$/.test(val)

// 验证手机号
export const isPhone = (val) => /^1(3|4|5|7|8|9)\d{9}$/.test(val)

// 验证账号 - 不能输入汉字
export const isAccount = (val) => /^[^\u4e00-\u9fa5]+$/.test(val)

五、扩展

1、本地打开 dist 文件夹下的 index.html

默认打包后,若直接在本地双击打开 index.html,通常会出现白屏。解决方法是在 vite.config.ts 中将 base 设置为 './'

import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'

export default defineConfig({
  base: './',
  plugins: [vue(), vueJsx()],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  }
})

2、Vite 项目中配置路径别名 @

使用 @ 替代冗长的 ../../ 路径几乎是刚需。分两步完成:

第一步,在 vite.config.ts 中配置:

import { resolve } from "path"
export default defineConfig({
  resolve: {
    alias: {
      "@": resolve(__dirname, "./src"),
    },
  },
})

第二步,在 tsconfig.jsoncompilerOptions 中添加:

"compilerOptions": {
  "baseUrl": ".",
  "paths": { "@/*": ["src/*"] }
}

完成后重启项目,即可使用 import xxx from '@/xxx' 的形式引入模块。

总结

本文详细介绍了从零搭建一个 Vue 3 + Vite + TypeScript + Axios + Element Plus 项目的完整流程,涵盖了代码规范、项目配置、环境变量、请求封装等关键环节。希望能为正在探索该技术栈的开发者提供有价值的参考,帮助大家少走弯路。实际项目中可能还会遇到各种细节问题,欢迎在实践中不断补充和完善。

来源:https://www.jb51.net/javascript/3624015wd.htm

游乐网为非赢利性网站,所展示的游戏/软件/文章内容均来自于互联网或第三方用户上传分享,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系youleyoucom@outlook.com。

同类文章
更多
AWS RDS 数据库配置入门与基础操作指南

AWS RDS 数据库配置入门与基础操作指南

本文介绍了AWSRDS的基本概念与核心价值,即提供托管式关系数据库服务,简化运维。详细阐述了创建RDS实例的关键配置步骤,包括引擎选择、实例规格、存储与网络设置。最后,指导读者如何通过多种方式安全连接至数据库实例,并开始进行数据操作,为后续应用开发奠定基础。

时间:2026-07-10 06:41
PHP MVC中AJAX请求无法调用控制器方法的原因与解决方案

PHP MVC中AJAX请求无法调用控制器方法的原因与解决方案

PHPMVC中AJAX请求返回整页HTML的常见原因是控制器方法未正确输出响应或未终止执行,导致框架渲染视图。解决方法是在控制器中设置JSON响应头、输出数据后调用exit()明确终止,同时前端使用小写url和dataType: "json "。

时间:2026-07-10 06:40
Go语言手动构造rsa.PublicKey:正确初始化大整数模数N完整指南

Go语言手动构造rsa.PublicKey:正确初始化大整数模数N完整指南

手动构造RSA公钥时,模数N为*big Int类型,不能直接使用超长十进制字面量,需通过SetString或UnmarshalText方法解析字符串。公钥指数E可直接赋值,推荐65537。生产环境应使用rsa GenerateKey生成密钥对,避免手动构造引发的安全和格式错误。

时间:2026-07-10 06:39
Go语言实现HTTP定时轮询监控多URL响应时间与状态检测

Go语言实现HTTP定时轮询监控多URL响应时间与状态检测

使用Go语言实现HTTP定时轮询监控,通过按行分割与Tab解析URL列表,避免闭包陷阱和nil指针,每个URL启动独立ticker安全并发请求,并配置超时控制与资源关闭,确保响应时间与状态码准确检测。

时间:2026-07-10 06:39
Tkinter中Label标签在主循环动态更新的正确方法

Tkinter中Label标签在主循环动态更新的正确方法

在Tkinter中正确动态更新标签的方法:将标签组件的textvariable参数绑定到一个StringVar变量,然后通过调用该变量的 set()方法更新其值,界面会自动刷新。这样避免直接修改text属性或调用update()。此做法实现数据与界面的解耦,代码更简洁,响应更及时,避免手动同步的闪烁,推荐做法。

时间:2026-07-10 06:39
热门专题
更多
刀塔传奇破解版无限钻石下载大全 刀塔传奇破解版无限钻石下载大全
洛克王国正式正版手游下载安装大全 洛克王国正式正版手游下载安装大全
思美人手游下载专区 思美人手游下载专区
好玩的阿拉德之怒游戏下载合集 好玩的阿拉德之怒游戏下载合集
不思议迷宫手游下载合集 不思议迷宫手游下载合集
百宝袋汉化组游戏最新合集 百宝袋汉化组游戏最新合集
jsk游戏合集30款游戏大全 jsk游戏合集30款游戏大全
宾果消消消原版下载大全 宾果消消消原版下载大全
  • 热门数据榜