Vue3+TS项目搭建

143 阅读2分钟

前言

一、创建Vue项目

  1. 方式1:Vue CLI
    • 基于Webpack
    • 命令:vue create
  2. 方式2:create-vue(推荐)
    • 基于Vite
    • 命令:npm init vue@latest
image.png

二、项目配置

image.png

1.配置环境

1.1..vscode

extensions.json推荐项目安装的插件。

image.png

1.2.env.d.ts

类型声明文件。

// 配置vue文件模块
declare module '*.vue' {
  import { DefineComponent } from 'vue'
  const component: DefineComponent
  export default component
}

2.配置代码规范

2.1集成editorConfig配置

跨编辑器保持代码风格统一。

  1. 新建.editorconfig文件。
  2. vscode安装EditorConfig for VS Code插件。
# .editorconfig
# http://editorconfig.org
root = true
[*] # 表示所有文件适用
charset = utf-8 # 设置文件字符集为 utf-8
indent_style = space # 缩进风格(tab | space)
indent_size = 2 # 缩进大小
end_of_line = lf # 控制换行类型(lf | cr | crlf)
trim_trailing_whitespace = true # 去除行尾的任意空白字符
insert_final_newline = true # 始终在文件末尾插入一个新行
[*.md] # 表示仅 md 文件适用以下规则
max_line_length = off
trim_trailing_whitespace = false

2.2使用prettier工具

项目代码格式化。

  1. 配置.prettierrc.json文件。(已经配置过了就跳过这一步)
{
  "useTabs": false,
  "tabWidth": 2,
  "printWidth": 80,
  "singleQuote": true,
  "trailingComma": "none",
  "semi": false
}
  1. vscode安装Prettier - Code formatter插件。
    • 配置Format On Save,勾选。 image.png
    • 配置Default Formatter,选择Prettier - Code formatterimage.png

2.3使用Eslint检测

  1. 项目安装eslint-plugin-prettier插件。(如果node_modules已经有就跳过这一步)。
  2. 配置.eslintrc.cjs文件。在extends中新增一个插件配置。
'plugin:prettier/recommended'
image.png
  1. 配完重启下编辑器。此时不规范代码会有提示。
image.png
  1. 砍臭艾斯后会自动fix并保存。
image.png

三、目录划分

  1. src目录下新增service、hooks、utils文件。

  2. css样式重置,assets目录下新增cssimages目录。

  3. 项目安装less插件和样式重置插件,npm i less -Dnpm i normalize.css -S

  4. css目录下新增index.lessreset.less文件。

  5. main.ts文件中引入normalize.csscss目录中的index.less

    image.png
image.png
  1. 配置用户代码片段。

    在线地址。

四、路由配置

新增404拦截

{
  path: '/:pathMatch(.*)*',
  name: 'NotFound',
  component: () => import('../views/not-found/NotFound.vue')
}

五、封装axios

见代码仓库中service模块。

六、开发环境和生产环境

  1. 项目根目录下新建.env、.env.development、.env.production环境变量文件。
  2. 文件中配置VITE_BASE_URL等内容。

附录

  1. 代码:vue3-ts-admin-template