【已开源】UniApp+Vue3+TS全栈实战:从0到1构建企业级跨端应用与规范、uniapp+vue3模板应用

发布于:2025-03-28 ⋅ 阅读:(25) ⋅ 点赞:(0)

在跨端开发日益成为主流的今天,如何高效构建规范、可维护的企业级应用?本文以UniApp+Vue3+TypeScript为核心技术栈,手把手带你从零搭建高标准的跨平台项目。

通过本文,你将系统掌握:

  • 环境配置:Node版本管理、Vite脚手架初始化、Vue3+TS工程化配置
  • 开发规范:ESLint+Prettier+Stylelint三剑客整合,Git提交自动化与Commitizen规范化
  • 进阶实战:Pinia全局状态管理、UnoCSS原子化样式、HTTP请求封装与反向代理实战
  • 工程扩展:UI库深度整合(uView-plus/wot-design-uni)、按需自动导入、多环境变量策略
  • 跨端适配:H5/小程序多平台编译与Nginx部署方案,破解跨域难题

无论你是初探UniApp生态,还是希望升级现有项目的工程化水平,本文都将提供从环境搭建到生产部署的全链路指南,助你打造高性能、高规范、跨端兼容的现代Web应用。代码即规范,开箱即用,开启高效开发之旅!

Gitee开源地址: https://gitee.com/moxunjinmu/uniapp-vue3-template

Github开源地址:https://github.com/moxunjinmu/uniapp-vue3-template

如果对你有点用的话欢迎Star✨✨✨,拜托啦~

一、环境准备

安装Node.js(推荐nvm安装管理node版本)

👉 NVM (Node Version Manager) 是一个用于管理多个 Node.js 版本的工具,便于在不同项目间切换 Node 环境

详细安装教程:莫循跃迁:nvm管理node版本速通👉 nvm(Node Version Manager)是一个用于管理Node.js - 掘金

配置效果

请添加图片描述

安装完成后,可以通过以下命令验证:

nvm -v

注意事项

  • 推荐使用 Node.js 16.x 或更高版本
  • 在 Windows 系统中,可能需要以管理员身份运行命令提示符

安装开发工具

安装VScode

👉 Visual Studio Code 是微软开发的轻量级代码编辑器,支持多种编程语言和丰富的插件扩展

下载地址:https://code.visualstudio.com/

或者安装cursor

👉 Cursor 是一款基于 AI 的代码编辑器,提供智能代码补全和建议功能

详细安装教程:《AI编程开发微信小程序》第一章:AI自动化编程神器Cursor基础使用教程嗨,大家好,我是莫循,一个用AI加速开发的 - 掘金

安装Vue CLI

👉 Vue CLI 是 Vue.js 官方提供的项目脚手架工具,用于快速创建和配置 Vue 项目

全局安装
npm install -g @vue/cli  # 默认安装最新版

权限问题

  • Windows:以管理员身份运行 CMD 或 PowerShell
  • Linux/Mac:添加 sudo 前缀(sudo npm install -g @vue/cli
验证安装
vue --version  # 显示版本号如 @vue/cli 5.0.8

常见错误

  • 'vue' 不是内部命令:检查环境变量是否包含 npm 全局路径(默认:C:\Users<用户>\AppData\Roaming\npm
  • 版本过低:通过 npm update -g @vue/cli 升级

二、创建项目

初始化项目

👉 按照 uni-app 官方文档 的步骤,通过 vue-cli 创建 uni-app + vue + typescript 脚手架:

npx degit dcloudio/uni-preset-vue#vite-ts uniapp-vue3-template

请添加图片描述

⚠️ 如果使用命令创建失败,可以通过 Gitee 下载 ZIP 包:vite-ts 分支

配置TypeScript编译器

👉 TypeScript 编译器配置文件决定了代码的编译规则和类型检查行为

默认生成的 TypeScript编译器配置文件 tsconfig.json 中继承的 @vue/tsconfig/tsconfig.json 文件不存在。因此,你需要移除此继承配置并添加相应的编译设置。

请添加图片描述

根据 TypeScript 官方配置文档,调整后的完整配置如下:

{
   
  "compilerOptions": {
   
    "module": "esnext",
    "moduleResolution": "node",
    "target": "esnext",
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
​
    "sourceMap": true,
    "baseUrl": ".",
    "paths": {
   
      "@/*": ["./src/*"]
    },
    "lib": ["esnext", "dom"],
    "types": ["@dcloudio/types", "vue"]
  },
  "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"],
  "exclude": ["node_modules", "dist"]
}

正确配置后,TypeScript 编译器将能够:

  • 识别 @/* 路径别名
  • 提供 Vue 和 uni-app 的类型支持
  • 对项目中的 .ts 和 .vue 文件进行类型检查 注意事项
  • 确保 types 数组中包含 @dcloudio/types 和 vue ,以获得完整的类型支持
  • 如果遇到类型错误,可能需要安装相应的类型定义包: npm install --save-dev @dcloudio/types @vue/runtime-core

三、核心配置

代码规范配置

配置ESLint

👉 ESLint 是一个静态代码分析工具,用于识别和报告 JavaScript/TypeScript 代码中的问题

VSCode 插件市场搜索 ESLint 插件并安装

安装插件

VSCode 插件市场搜索 ESLint 插件并安装

请添加图片描述

通过以下命令快速生成 ESLint 配置文件:

npx eslint --init
配置过程
PS D:\700-code\750-Gitee\uniapp-vue3-template> npx eslint --init
You can also run this command directly using 'npm init @eslint/config@latest'.
@eslint/create-config: v1.6.0
​
√ How would you like to use ESLint? · problems    
√ What type of modules does your project use? · esm
√ Which framework does your project use? · vue
√ What type of modules does your project use? · esm
√ What type of modules does your project use? · esm
√ Which framework does your project use? · vue
√ What type of modules does your project use? · esm
√ What type of modules does your project use? · esm
√ Which framework does your project use? · vue
√ Does your project use TypeScript? · typescript
√ Does your project use TypeScript? · typescript
√ Where does your code run? · browser
√ Where does your code run? · browser
The config that you've selected requires the following dependencies:
The config that you've selected requires the following dependencies:
​
​
eslint, globals, @eslint/js, typescript-eslint, eslint-plugin-vue
eslint, globals, @eslint/js, typescript-eslint, eslint-plugin-vue
√ Would you like to install them now? · No / Yes
√ Would you like to install them now? · No / Yes
√ Which package manager do you want to use? · pnpm
√ Which package manager do you want to use? · pnpm
☕️Installing...
☕️Installing...
 WARN  7 deprecated subdependencies found: abab@2.0.6, domexception@2.0.1, glob@7.2.3, inflight@1.0.6, phin@2.9.3, rimraf@3.0.2, w3c-hr-time@1.0.2
Packages: +72
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Progress: resolved 863, reused 790, downloaded 32, added 72, done
 WARN  Issues with peer dependencies found
.
└─┬ @dcloudio/uni-automator 3.0.0-4030620241128001
  └─┬ @dcloudio/uni-cli-shared 3.0.0-4030620241128001
    └─┬ @vue/server-renderer 3.4.21
      └── ✕ unmet peer vue@3.4.21: found 3.5.13
​
​
devDependencies:
+ @eslint/js 9.23.0
+ eslint 9.23.0
+ eslint-plugin-vue 10.0.0
+ globals 16.0.0
+ typescript-eslint 8.27.0
​
Done in 6.1s
Done in 6.1s
Successfully created D:\700-code\750-Gitee\uniapp-vue3-template\eslint.config.mjs file.

执行该命令后,ESLint 会通过交互式问题的方式,帮助生成配置文件。针对 9.x 版本,默认会生成基于 Flat Config 格式的 eslint.config.mjs 文件,与之前的 .eslintrc 格式有所不同。

默认生成的 eslint.config.mjs 文件如下所示:

请添加图片描述

在此基础上,可以根据项目的需求进行一些定制化配置,例如添加忽略规则或自定义的特殊规则。

import globals from "globals"; // 全局变量配置
import pluginJs from "@eslint/js"; // JavaScript 的推荐配置
import tseslint from "typescript-eslint"; // TypeScript 配置
import pluginVue from "eslint-plugin-vue"; // Vue 配置
​
export default [
  {files: ["**/*.{js,mjs,cjs,ts,vue}"]}, // 校验的文件类型
  {languageOptions: { globals: {...globals.browser , ...globals.node} }}, // 浏览器/Node环境全局变量
  pluginJs.configs.recommended, // JavaScript 推荐配置
  ...tseslint.configs.recommended, // TypeScript 推荐配置
  ...pluginVue.configs["flat/essential"], // Vue 推荐配置
  { files: ["**/*.vue"], languageOptions: { parserOptions: { parser: tseslint.parser } } }, // 对 .vue 文件使用 TypeScript 解析器
  
  // 添加忽略的文件或目录
  {
    ignores: [
      "/dist",
      "/public",
      "/node_modules",
      "**/*.min.js",
      "**/*.config.mjs",
      "**/*.tsbuildinfo",
      "/src/manifest.json",
    ]
  },
​
  // 自定义规则
  {
    rules: {
      quotes: ["error", "double"], // 强制使用双引号
      "quote-props": ["error", "always"], // 强制对象的属性名使用引号
      semi: ["error", "always"], // 要求使用分号
      indent: ["error", 2], // 使用两个空格进行缩进
      "no-multiple-empty-lines": ["error", { max: 1 }], // 不允许多个空行
      "no-trailing-spaces": "error", // 不允许行尾有空格
​
      // TypeScript 规则
      "@typescript-eslint/no-explicit-any": "off", // 禁用 no-explicit-any 规则,允许使用 any 类型
      "@typescript-eslint/explicit-function-return-type": "off", // 不强制要求函数必须明确返回类型
      "@typescript-eslint/no-empty-interface": "off", // 禁用 no-empty-interface 规则,允许空接口声明
      "@typescript-eslint/no-empty-object-type": "off", // 允许空对象类型
​
      // Vue 规则
      "vue/multi-word-component-names": "off", // 关闭多单词组件名称的限制
      "vue/html-indent": ["error", 2], // Vue 模板中的 HTML 缩进使用两个空格
      "vue/no-v-html": "off", // 允许使用 v-html (根据实际项目需要)
    },
  },
];
添加 ESLint 脚本

👉 在 package.json 中添加 lint 命令,方便执行代码检查

为了方便使用 ESLint,可以在 package.json 中添加 lint 脚本命令:

{
   
  "scripts": {
   
    "lint:eslint": "eslint --fix ./src",
    "lint": "npm run lint:eslint"
  }
}

此脚本会自动修复符合 ESLint 规则的代码问题,并输出检查结果。

测试效果

App.vue 文件中声明一个未使用的变量,并运行 pnpm run lint,可以看到 ESLint 提示该变量未使用。如下图所示:

请添加图片描述

请添加图片描述

这里多报了一个错误显示 ‘@typescript-eslint/ban-types’ was not found,查找解决方法,需要安装依赖。我们执行下方命令:

> npm install --save-dev @typescript-eslint/eslint-plugin @typescript-eslint/parser

重新执行pnpm run lint ,结果:

请添加图片描述

安装解析器

👉 vue-eslint-parser 是专门用于解析 .vue 文件的 ESLint 解析器

pnpm install vue-eslint-parser --save-dev

请添加图片描述

针对不同文件配置插件和解析器:

// eslint.config.mjs
import globals from "globals";
import js from "@eslint/js";
​
// ESLint 核心插件
import pluginVue from "eslint-plugin-vue";
import pluginTypeScript from "@typescript-eslint/eslint-plugin";
​
// Prettier 插件及配置
import configPrettier from "eslint-config-prettier";
import pluginPrettier from "eslint-plugin-prettier";
​
// 解析器
import * as parserVue from "vue-eslint-parser";
import * as parserTypeScript from "@typescript-eslint/parser";
​
// 定义 ESLint 配置
export default [
  // 通用 JavaScript/TypeScript 配置
  {
    ...js.configs.recommended,
    ignores: [
      "/dist",
      "/public",
      "/node_modules",
      "**/*.min.js",
      "**/*.config.mjs",
      "**/*.tsbuildinfo",
      "/src/manifest.json",
    ],
    languageOptions: {
      globals: {
        ...globals.browser, // 浏览器变量 (window, document 等)
        ...globals.node, // Node.js 变量 (process, require 等)
      },
    },
    plugins: {
      prettier: pluginPrettier,
    },
    rules: {
      ...configPrettier.rules,
      ...pluginPrettier.configs.recommended.rules,
      "no-debug": "off", // 允许使用 debugger
      "prettier/prettier": [
        "error",
        {
          endOfLine: "auto", // 解决换行符冲突
        },
      ],
    },
  },
​
  // TypeScript 配置
  {
    files: ["**/*.?([cm])ts"],
    languageOptions: {
      parser: parserTypeScript,
      parserOptions: {
        sourceType: "module",
      },
    },
    plugins: {
      "@typescript-eslint": pluginTypeScript,
    },
    rules: {
      ...pluginTypeScript.configs.recommended.rules,
      "@typescript-eslint/no-explicit-any": "off", // 允许使用 any
      "@typescript-eslint/no-empty-function": "off", // 允许空函数
      "@typescript-eslint/no-empty-object-type": "off", // 允许空对象类型
      "@typescript-eslint/consistent-type-imports": [
        "error",
        { disallowTypeAnnotations: false, fixStyle: "inline-type-imports" },
      ], // 统一类型导入风格
    },
  },
​
  // TypeScript 声明文件的特殊配置
  {
    files: ["**/*.d.ts"],
    rules: {
      "eslint-comments/no-unlimited-disable": "off", // 关闭 eslint 注释相关规则
      "unused-imports/no-unused-vars": "off", // 忽略未使用的导入
    },
  },
​
  // JavaScript (commonjs) 配置
  {
    files: ["**/*.?([cm])js"],
    rules: {
      "@typescript-eslint/no-var-requires": "off", // 允许 require
    },
  },
​
  // Vue 文件配置
  {
    files: ["**/*.vue"],
    languageOptions: {
      parser: parserVue,
      parserOptions: {
        parser: "@typescript-eslint/parser",
        sourceType: "module",
      },
    },
    plugins: {
      vue: pluginVue,
    },
    processor: pluginVue.processors[".vue"],
    rules: {
      ...pluginVue.configs["vue3-recommended"].rules,
      "vue/no-v-html": "off", // 允许 v-html
      "vue/require-default-prop": "off", // 允许没有默认值的 prop
      "vue/multi-word-component-names": "off", // 关闭组件名称多词要求
      "vue/html-self-closing": [
        "error",
        {
          html: { void: "always", normal: "always", component: "always" },
          svg: "always",
          math: "always",
        },
      ], // 自闭合标签
    },
  },
];

集成 Prettier

👉 Prettier 是一个代码格式化工具,可以强制执行一致的代码风格

prettier 中文网https://prettier.nodejs.cn/

安装插件

VSCode 插件市场搜索 Prettier - Code formatter 插件安装

请添加图片描述

安装依赖
pnpm install -D prettier eslint-config-prettier eslint-plugin-prettier 

请添加图片描述

  • prettier:主要的 Prettier 格式化库。
  • eslint-plugin-prettier:将 Prettier 的规则作为 ESLint 的规则来运行。
  • eslint-config-prettier:禁用所有与格式相关的 ESLint 规则,以避免和 Prettier 的冲突。
配置 Prettier

👉 以下是 Prettier 配置文件,定义了代码格式化的规则

项目根目录下新建配置文件 prettier.config.mjs,添加常用规则:

export default {
  printWidth: 100, // 每行最多字符数量,超出换行(默认80)
  tabWidth: 2, // 缩进空格数,默认2个空格
  useTabs: false, // 指定缩进方式,空格或tab,默认false,即使用空格
  semi: true, // 使用分号
  singleQuote: false, // 使用单引号 (true:单引号;false:双引号)
  trailingComma: 'all', // 末尾使用逗号
};
配置忽略文件

项目根目录新建 .prettierignore 文件指定 Prettier 不需要格式化的文件和文件夹

.prettierignore
node_modules
dist
public
*.min.js
添加格式化脚本

package.json 文件中添加:

{
   
    "scripts": {
   
        "format": "prettier --write ./src"
    }
}

请添加图片描述

保存自动格式化

打开 VSCode 的 FilePreferencesSettings,然后选择 Open Settings (JSON),添加以下配置

{
   
  "editor.formatOnSave": true, // 保存格式化文件
  "editor.defaultFormatter": "esbenp.prettier-vscode" // 指定 prettier 为所有文件默认格式化器
}

集成 Stylelint

👉 Stylelint 一个强大的 CSS linter(检查器),可帮助您避免错误并强制执行约定。

Stylelint 官网https://stylelint.io/

安装插件

VSCode 插件搜索 Stylelint 并安装

请添加图片描述

安装依赖
pnpm install -D postcss postcss-html postcss-scss stylelint stylelint-config-recommended stylelint-config-recommended-scss stylelint-config-recommended-vue stylelint-config-recess-order stylelint-config-html stylelint-prettier

表格 还在加载中,请等待加载完成后再尝试复制

配置 Stylelint

根目录新建 .stylelintrc.cjs 文件,配置如下:

module.exports = {
  extends: [
    "stylelint-config-recommended",
    "stylelint-config-recommended-scss",
    "stylelint-config-recommended-vue/scss",
    "stylelint-config-html/vue",
    "stylelint-config-recess-order"
  ],
  plugins: ["stylelint-prettier"],
  overrides: [
    {
      files: ["**/*.{vue,html}"],
      customSyntax: "postcss-html"
    },
    {
      files: ["**/*.{css,scss}"],
      customSyntax: "postcss-scss"
    }
  ],
  rules: {
    "import-notation": "string",
    "selector-class-pattern": null,
    "custom-property-pattern": null,
    "keyframes-name-pattern": null,
    "no-descending-specificity": null,
    "no-empty-source": null,
    "selector-pseudo-class-no-unknown": [
      true,
      {
        ignorePseudoClasses: ["global", "export", "deep"]
      }
    ],
    "unit-no-unknown": [
      true, 
      {
        ignoreUnits: ["rpx"]
      }
    ],
    "property-no-unknown": [
      true,
      {
        ignoreProperties: []
      }
    ],
    "at-rule-no-unknown": [
      true,
      {
        ignoreAtRules: ["apply", "use", "forward"]
      }
    ]
  }
};
配置忽略文件

根目录创建 .stylelintignore 文件,配置忽略文件如下:

*.min.js
dist
public
node_modules
添加 Stylelint 脚本

package.json 添加 Stylelint 检测指令:

  "scripts": {
   
      "lint:stylelint": "stylelint  "**/*.{css,scss,vue,html}" --fix"
  }
保存自动修复

项目根目录下.vscode/settings.json 文件添加配置:

{
   
  "editor.codeActionsOnSave": {
   
    "source.fixAll.stylelint": true 
  },
  "stylelint.validate": ["css", "scss", "vue", "html"]
}

为了验证把尺寸属性 width 放置在定位属性 position 前面,根据 CSS 书写顺序规范 推断是不符合规范的,在保存时 Stylelint 自动将属性重新排序,达到预期。

测试

执行以下命令进行检测

npm run lint:stylelint

Git提交规范配置

👉 配置 Husky 的 pre-commitcommit-msg 钩子,实现代码提交的自动化检查和规范化。

  • pre-commit: 使用 Husky + Lint-staged,在提交前进行代码规范检测和格式化。确保项目已配置 ESLint、Prettier 和 Stylelint。
  • commit-msg: 结合 Husky、Commitlint、Commitizen 和 cz-git,生成规范化且自定义的 Git commit 信息。

集成 Husky

👉 Husky 是 Git 钩子工具,可以设置在 git 各个阶段(pre-commitcommit-msg 等)触发。

Husky官网https://typicode.github.io

请添加图片描述

安装依赖
pnpm add -D husky
初始化

init 命令简化了项目中的 husky 设置。它会在 .husky/ 中创建 pre-commit 脚本,并更新 package.json 中的 prepare 脚本。

pnpm exec husky init

默认生成了 pnpm test ,改成 echo "Running pre-commit hook..."测试功能

echo "Running pre-commit hook..."
测试

请添加图片描述

请添加图片描述

通过 pre-commit 钩子,可以自动运行各种代码检查工具,在提交代码前强制执行代码质量和样式检查。常见的工具包括:

  • eslint:用于检查和修复 JavaScript/TypeScript 代码中的问题。
  • stylelint:用于检测和修复 CSS/SCSS 样式问题。

接下来,集成 lint-stagedcommitlint 来进一步完善开发体验。

集成 lint-staged

👉 lint-staged 是一个工具,专门用于只对 Git 暂存区的文件运行 lint 或其他任务,确保只检查和修复被修改或新增的代码部分,而不会影响整个代码库。这样可以显著提升效率,尤其是对于大型项目。

安装依赖

使用以下命令安装 lint-staged

pnpm add -D lint-staged
配置 lint-staged

package.json 中添加 lint-staged 配置,确保在 pre-commit 阶段自动检测暂存的文件:

{
   
  "name": "vue-uniapp-template",
  "version": "0.0.0",
  "lint-staged": {
   
    "*.{js,ts}": [
      "eslint --fix",
      "prettier --write"
    ]