Appearance
day01 初始化
目录
一、创建项目
1.HBuilderx可视化的方式创建项目
HBuilderx内置less、sass、pinia等包,无需手动安装
2.使用命令行的方式创建
markdown
npx degit dcloudio/uni-preset-vue#vite-ts my-vue3-project优点是不用受限于HBuilderx工具的方式创建。我们可以结合vscode开发使用。因为VS Code 对 TS 类型支持友好,前端主流编辑器不用重新适应其他编辑器。
但是我们要安装额外的插件辅助我们开发。
安装 uni-app 插件
- 👉 安装 uni-app 开发插件
- uni-create-view :快速创建 uni-app 页面
- uni-helper :uni-app 代码提示
- uniapp 小程序扩展 :鼠标悬停查文档
- 👉 TS 类型校验
- 安装 类型声明文件
pnpm i -D miniprogram-api-typings @uni-helper/uni-app-types - 配置
tsconfig.json
- 安装 类型声明文件
- 👉 JSON 注释问题
- 设置文件关联,把
manifest.json和pages.json设置为jsonc
- 设置文件关联,把
参考
typescript
// tsconfig.json
{
"extends": "@vue/tsconfig/tsconfig.json",
"compilerOptions": {
"sourceMap": true,
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
},
"lib": ["esnext", "dom"],
// 类型声明文件
"types": [
"@dcloudio/types", // uni-app API 类型
"miniprogram-api-typings", // 原生微信小程序类型
"@uni-helper/uni-app-types" // uni-app 组件类型
]
},
// vue 编译器类型,校验标签类型
"vueCompilerOptions": {
// 小程序原生标签飘红配置这一个选项可解决
"plugins": ["@uni-helper/uni-app-types/volar-plugin"]
},
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"]
}工作区设置参考
json
typescript
// .vscode/settings.json
{
// 在保存时格式化文件
"editor.formatOnSave": true,
// 文件格式化配置
"[json]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
// 配置语言的文件关联
"files.associations": {
"pages.json": "jsonc", // pages.json 可以写注释
"manifest.json": "jsonc" // manifest.json 可以写注释
}
}二、数据持久化
要注意pinia的使用,选项式和组合式。
直接使用pinia数据持久化插件。
bash
pnpm add pinia pinia-plugin-persistedstate以前的持久化我们一般使用localstorage或sessionstorage。但在uni中要适应多端的需求,我们需要自己定义插件的本地存储方式。
typescript
import { defineStore } from 'pinia'
import { ref } from 'vue'
// 定义 Store
export const useMemberStore = defineStore(
'member',
() => {
// 会员信息
const profile = ref<any>()
// 保存会员信息,登录时使用
const setProfile = (val: any) => {
profile.value = val
}
// 清理会员信息,退出时使用
const clearProfile = () => {
profile.value = undefined
}
// 记得 return
return {
profile,
setProfile,
clearProfile,
}
},
// TODO: 持久化
{
persist: {
//自定义多端存储方法
storage: {
getItem: (key: string): string => {
return uni.getStorageSync(key)
},
setItem: (key: string, value: string) => {
uni.setStorageSync(key, value)
},
},
},
},
)typescript
import { createPinia } from 'pinia'
import persist from 'pinia-plugin-persistedstate'
// 创建 pinia 实例
const pinia = createPinia()
// 使用持久化存储插件
pinia.use(persist)
// 默认导出,给 main.ts 使用
export default pinia
// 模块统一导出
export * from './modules/member'然后再其他地方使用。
vue
<script setup lang="ts">
import { useMemberStore } from '@/stores'
const memberStore = useMemberStore()
</script>
<template>
<view class="my">
<view>会员信息:{{ memberStore.profile }}</view>
<button @tap="
memberStore.setProfile({
nickname: '黑马先锋',
})
" size="mini" plain>
保存用户信息
</button>
<button @tap="memberStore.clearProfile()" size="mini" plain>清理用户信息</button>
</view>
</template>如果安装持久化插件之后,运行项目报错[vite]: Rollup failed to resolve import....,可降低插件版本到3.2.0
三、uni.request 请求封装
1.使用promise封装请求
typescript
// 用promise封装请求.对返回的信息统一处理。
export const http = (options:UniApp.RequestOptions)=>{
return new Promise((resolve,reject)=>{
uni.request({
...options,
success(res){
//接口访问成功
resolve(res)
console.log(res)
},
fail(err){
//接口访问失败
reject(err)
}
})
})
}2.使用拦截器
typescript
const baseURL = 'https://pcapi-xiaotuxian-front-devtest.itheima.net'
// 拦截请求。在请求之前加上其他信息
const intercept={
invoke(args:UniApp.RequestOptions) {
// request 触发前拼接 url
if(!args.url.startsWith('http')){
args.url = baseURL+args.url
}
args.timeout=10000
args.header['source-client']='miniapp'
const Authorization=uni.getStorageSync('token')
if(Authorization){
args.header.Authorization = Authorization
}
}
}
uni.addInterceptor('request',intercept)四、代码规范
1.统一代码风格eslint + prettier
bash
pnpm i -D eslint prettier eslint-plugin-vue @vue/eslint-config-prettier @vue/eslint-config-typescript @rushstack/eslint-patch @vue/tsconfig- eslint 。 ESLint < v9 。
- prettier
- eslint-plugin-vue
- @vue/eslint-config-prettier,使用
.eslintrc.cjs格式的配置文件需要使用9或者更早的版本。主要用于解决prettier和eslint之间的冲突,一般与@rushstack/eslint-patch结合使用。 - @vue/eslint-config-typescript,使用
.eslintrc.cjs格式的配置文件需要使用13或者更早的版本,一般与@rushstack/eslint-patch结合使用。 - @rushstack/eslint-patch, 是eslint补丁,增强 ESLint,更好地支持大规模 monorepos。解决 ESLint 中的已知限制,不必安装太多依赖项。
新建 .eslintrc.cjs 文件,添加以下 eslint 配置。使用 .eslintrc.* 文件配置规则需要 ESLint < v9 。
typescript
/* 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',
'@vue/eslint-config-prettier',
],
// 小程序全局变量
globals: {
uni: true,
wx: true,
WechatMiniprogram: true,
getCurrentPages: true,
getApp: true,
UniApp: true,
UniHelper: true,
App: true,
Page: true,
Component: true,
AnyObject: true,
},
parserOptions: {
ecmaVersion: 'latest',
},
rules: {
'prettier/prettier': [
'warn',
{
singleQuote: true,
semi: false,
printWidth: 100,
trailingComma: 'all',
endOfLine: 'auto',
},
],
'vue/multi-word-component-names': ['off'],
'vue/no-setup-props-destructure': ['off'],
'vue/no-deprecated-html-element-is': ['off'],
'@typescript-eslint/no-unused-vars': ['off'],
},
}- 配置
package.json
json
{
"script": {
// ... 省略 ...
"lint": "eslint . --ext .vue,.js,.ts --fix --ignore-path .gitignore"
}
}bash
pnpm lint2.Git 工作流规
(1) husky
操作 git 钩子的工具,可以设置在 git 各个阶段(pre-commit、commit-msg 等)触发
bash
pnpm dlx husky-init(2) lint-staged
本地暂存代码检查工具
bash
"
pnpm i -D lint-stagedjson
{
"script": {
// ... 省略 ...
"lint-staged": "lint-staged"
},
"lint-staged": {
"*.{vue,ts,js}": ["eslint --fix"]
}
}或者添加更多不同文件在 git 提交执行的 lint 检测配置
javascript
"lint-staged": {
"*.{js,ts}": [
"eslint --fix",
"prettier --write"
],
"*.{cjs,json}": [
"prettier --write"
],
"*.{vue,html}": [
"eslint --fix",
"prettier --write",
"stylelint --fix"
],
"*.{scss,css}": [
"stylelint --fix",
"prettier --write"
],
"*.md": [
"prettier --write"
]
}bash
npm run lint-staged(3) Commitlint
Commitlint 检查您的提交消息是否符合 Conventional commit format。-- Commitlint 官网
bash
npm install -D @commitlint/cli @commitlint/config-conventional以上两个库开发项目时我用的版本是17.8.1。
根目录创建 commitlint.config.cjs 配置文件,示例配置: @commitlint/config-conventional
javascript
module.exports = {
// 继承的规则
extends: ["@commitlint/config-conventional"],
// @see: https://commitlint.js.org/#/reference-rules
rules: {
"subject-case": [0], // subject大小写不做校验
// 类型枚举,git提交type必须是以下类型
"type-enum": [
2,
"always",
[
'feat', // 新增功能
'fix', // 修复缺陷
'docs', // 文档变更
'style', // 代码格式(不影响功能,例如空格、分号等格式修正)
'refactor', // 代码重构(不包括 bug 修复、功能新增)
'perf', // 性能优化
'test', // 添加疏漏测试或已有测试改动
'build', // 构建流程、外部依赖变更(如升级 npm 包、修改 webpack 配置等)
'ci', // 修改 CI 配置、脚本
'revert', // 回滚 commit
'chore', // 对构建过程或辅助工具和库的更改(不影响源文件、测试用例)
],
],
},
};(4) Commitizen & cz-git
commitizen: 基于Node.js的 git commit 命令行工具,辅助生成标准化规范化的 commit message。 cz-git: 一款工程性更强,轻量级,高度自定义,标准输出格式的 commitizen 适配器。- 配置参考官方文档
bash
npm install -D commitizen cz-git配置文件
javascript
// commitlint.config.cjs
module.exports = {
rule: {
...
},
prompt: {
messages: {
type: '选择你要提交的类型 :',
scope: '选择一个提交范围(可选):',
customScope: '请输入自定义的提交范围 :',
subject: '填写简短精炼的变更描述 :\n',
body: '填写更加详细的变更描述(可选)。使用 "|" 换行 :\n',
breaking: '列举非兼容性重大的变更(可选)。使用 "|" 换行 :\n',
footerPrefixesSelect: '选择关联issue前缀(可选):',
customFooterPrefix: '输入自定义issue前缀 :',
footer: '列举关联issue (可选) 例如: #31, #I3244 :\n',
generatingByAI: '正在通过 AI 生成你的提交简短描述...',
generatedSelectByAI: '选择一个 AI 生成的简短描述:',
confirmCommit: '是否提交或修改commit ?',
},
// prettier-ignore
types: [
{ value: "feat", name: "特性: ✨ 新增功能", emoji: ":sparkles:" },
{ value: "fix", name: "修复: 🐛 修复缺陷", emoji: ":bug:" },
{ value: "docs", name: "文档: 📝 文档变更", emoji: ":memo:" },
{ value: "style", name: "格式: 💄 代码格式(不影响功能,例如空格、分号等格式修正)", emoji: ":lipstick:" },
{ value: "refactor", name: "重构: ♻️ 代码重构(不包括 bug 修复、功能新增)", emoji: ":recycle:" },
{ value: "perf", name: "性能: ⚡️ 性能优化", emoji: ":zap:" },
{ value: "test", name: "测试: ✅ 添加疏漏测试或已有测试改动", emoji: ":white_check_mark:"},
{ value: "build", name: "构建: 📦️ 构建流程、外部依赖变更(如升级 npm 包、修改 vite 配置等)", emoji: ":package:"},
{ value: "ci", name: "集成: 🎡 修改 CI 配置、脚本", emoji: ":ferris_wheel:"},
{ value: "revert", name: "回退: ⏪️ 回滚 commit",emoji: ":rewind:"},
{ value: "chore", name: "其他: 🔨 对构建过程或辅助工具和库的更改(不影响源文件、测试用例)", emoji: ":hammer:"},
],
useEmoji: true,
emojiAlign: 'center',
useAI: false,
aiNumber: 1,
themeColorCode: '',
scopes: [],
allowCustomScopes: true,
allowEmptyScopes: true,
customScopesAlign: 'bottom',
customScopesAlias: 'custom',
emptyScopesAlias: 'empty',
upperCaseSubject: false,
markBreakingChangeMode: false,
allowBreakingChanges: ['feat', 'fix'],
breaklineNumber: 100,
breaklineChar: '|',
skipQuestions: [],
issuePrefixes: [{ value: 'closed', name: 'closed: ISSUES has been processed' }],
customIssuePrefixAlign: 'top',
emptyIssuePrefixAlias: 'skip',
customIssuePrefixAlias: 'custom',
allowCustomIssuePrefix: true,
allowEmptyIssuePrefix: true,
confirmColorize: true,
maxHeaderLength: Infinity,
maxSubjectLength: Infinity,
minSubjectLength: 0,
scopeOverrides: undefined,
defaultBody: '',
defaultIssues: '',
defaultScope: '',
defaultSubject: '',
}
}修改 package.json 添加 config 指定使用的适配器
json
"config": {
"commitizen": {
"path": "node_modules/cz-git"
}
}添加提交指令
json
"scripts": {
"commit": "git-cz"
}cz-git 验证
执行 commit 指令进行代码提交流程,执行前需将改动的文件通过 git add 添加到暂存区
bash
npm run commit