UniApp 常用插件配置详解
·
Pinia (状态管理)
// main.js
import { createApp } from 'vue'
import { createPinia } from 'pinia'
const pinia = createPinia()
const app = createApp(App)
app.use(pinia)
功能说明:
- Vue 3 官方推荐的状态管理库
- 替代 Vuex 的轻量级解决方案
- 提供 Store 概念管理全局状态
- 支持 TypeScript 类型推断
使用方法:
// stores/user.js
import { defineStore } from 'pinia'
export const useUserStore = defineStore('user', {
state: () => ({
name: '张三',
age: 25
}),
actions: {
updateName(newName) {
this.name = newName
}
},
getters: {
doubleAge: (state) => state.age * 2
}
})
// 组件中使用
import { useUserStore } from '@/stores/user'
const userStore = useUserStore()
console.log(userStore.name) // 获取状态
userStore.updateName('李四') // 调用action
2. pinia-plugin-persistedstate (持久化存储)
// main.js
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)
功能说明:
- 为 Pinia 添加持久化存储功能
- 自动将状态保存到 localStorage/sessionStorage
- 支持自定义存储方式和加密
使用方法:
// stores/user.js
export const useUserStore = defineStore('user', {
persist: {
key: persistKey,
paths: ['token', 'permissions'],
// #ifdef MP
storage: {
getItem(key) {
return uni.getStorageSync(key)
},
setItem(key, value) {
uni.setStorageSync(key, value)
}
}
// #endif
},
// ...其他配置
})
3. uView Plus (UI组件库)
// main.js
import uViewPlus from 'uview-plus'
import 'uview-plus/index.scss'
app.use(uViewPlus)
功能说明:
- 基于 UniApp 的 UI 组件库
- 提供 60+ 高质量组件
- 支持主题定制和暗黑模式
- 完善的 TypeScript 支持
使用方法:
<template>
<u-button type="primary">主要按钮</u-button>
<u-calendar v-model="show"></u-calendar>
</template>
<script>
export default {
data() {
return {
show: false
}
}
}
</script>
4. vConsole (移动端调试工具)
// main.js
import VConsole from 'vconsole'
// 开发环境下启用
if (process.env.NODE_ENV === 'development') {
new VConsole()
}
功能说明:
- 移动端网页调试面板
- 查看 console 日志、网络请求
- 查看页面 DOM 结构
- 支持性能分析
使用方法:
// 直接使用console.log等API
console.log('调试信息')
console.warn('警告信息')
console.error('错误信息')
5. ESLint (代码质量检查)
// eslint.config.mjs
import js from '@eslint/js'
import globals from 'globals'
import tseslint from 'typescript-eslint'
import pluginVue from 'eslint-plugin-vue'
import json from '@eslint/json'
import css from '@eslint/css'
import { defineConfig } from 'eslint/config'
import eslintPluginPrettierRecommended from 'eslint-plugin-prettier/recommended'
export default defineConfig([
{ files: ['**/*.{js,mjs,cjs,ts,mts,cts,vue}'], plugins: { js }, extends: ['js/recommended'] },
{
files: ['**/*.{js,mjs,cjs,ts,mts,cts,vue}'],
languageOptions: { globals: { ...globals.browser, ...globals.node, uni: 'readonly', UniApp: 'readonly' } }
},
tseslint.configs.recommended,
eslintPluginPrettierRecommended,
pluginVue.configs['flat/base'],
{ ignores: ['dist/**', 'node_modules/**', '*.ts', 'src/static/**', 'src/*.json', 'src/*.d.ts', '/*.d.ts'] },
{
rules: {
'no-const-assign': 2, //禁止修改const声明的变量
'no-dupe-keys': 2, //在创建对象字面量时不允许键重复 {a:1,a:1}
'no-dupe-args': 2, //函数参数不能重复
'no-duplicate-case': 2, //switch中的case标签不能重复
'no-empty': 2, //块语句中的内容不能为空
'no-empty-character-class': 2, //正则表达式中的[]内容不能为空
'no-extra-parens': 2, //禁止非必要的括号
'no-extra-semi': 2, //禁止多余的冒号
'no-fallthrough': 1, //禁止switch穿透
'no-func-assign': 2, //禁止重复的函数声明
'no-undef': 1, //不能有未定义的变量
'no-undef-init': 2, //变量初始化时不能直接给它赋值为undefined
curly: [2, 'all'], //必须使用 if(){} 中的{}
quotes: [1, 'single'], //引号类型 `` "" ''
'comma-dangle': [2, 'never'], //对象字面量项尾不能有逗号
'no-var': 0, //禁用var,用let和const代替
'no-array-constructor': 2, //禁止使用数组构造器
'no-bitwise': 0, //禁止使用按位运算符
'no-caller': 1, //禁止使用arguments.caller或arguments.callee
'no-alert': 0 //禁止使用alert confirm prompt
}
},
{
files: ['**/*.vue'],
languageOptions: { parserOptions: { parser: tseslint.parser } }
},
{ files: ['**/*.json'], plugins: { json }, language: 'json/json', extends: ['json/recommended'] },
{ files: ['**/*.css'], plugins: { css }, language: 'css/css', extends: ['css/recommended'] }
])
功能说明:
- JavaScript/TypeScript 代码检查工具
- 强制执行代码风格规范
- 发现潜在代码问题
- 支持 Vue 3 语法检查
使用方法:
# 引入
npm init @eslint/config@latest --save-dev
# 检查代码
npx eslint src/
# 自动修复问题
npx eslint src/ --fix
安装必要的 ESlint 扩展插件
扩展插件说明:
- @eslint/js: 附带ESLint 团队推荐的规则,用于给下面其他扩展插件自定义配置扩展对象时,提供一个默认推荐规则。
- typescript-eslint:能够支持typescript 语法检查。
- eslint-plugin-vue:能够支持 vue.js 语法检查,并且能够识别 .vue 文件。
如果使用 ESlint 的时候选择了支持 vue 和 typescript ,那么生成的 eslint.config.mjs 中已经引入了 typescript-eslint 插件和 eslint-plugin-vue 插件,无需再配置了。
如果没有请安装:
npm install --save-dev typescript-eslint eslint-plugin-vue
6. Prettier (代码格式化)
# 引入
npm install --save-dev --save-exact prettier
// prettier.config.mjs
const config = {
semi: false, // 不尾随分号
singleQuote: true, // 使用单引号
printWidth: 120, // 每行最大字符数
tabWidth: 4, // 缩进字符数
useTabs: false, // 使用空格代替tab
trailingComma: 'none', // 尾随逗号
bracketSpacing: true, // 对象大括号内两边是否加空格 { a:0 }
arrowParens: 'avoid', // 单个参数的箭头函数不加括号 x => x
endOfLine: 'auto' // 行尾换行符
}
export default config
功能说明:
- 代码格式化工具
- 自动统一代码风格
- 支持多种语言(JS/TS/HTML/CSS等)
- 与 ESLint 配合使用
使用方法:
# 格式化所有文件
npx prettier --write .
# 检查格式化问题
npx prettier --check .
安装必要的 Prettier 扩展插件
在 Prettier 官方文档-Integrating with Linters 里,已经提到如何通过安装扩展插件来解决 ESlint 与 Prettier 冲突或不必要的规则问题:
扩展插件说明:
- eslint-config-prettier: 关闭所有不必要或可能与Prettier冲突的规则。注意这个插件仅关闭规则,需要搭配下面的 eslint-plugin-prettier 来使用。
- eslint-plugin-prettier: 将 Prettier 作为 ESlint 的扩展插件,成为 ESlint 语法检查规则的扩展部分。
安装步骤:
npm install --save-dev eslint-plugin-prettier eslint-config-prettier
在 eslint.config.js 文件中配置数组的末尾添加如下:
// eslint.config.js
// 导入这个可以一次性设置 eslint-plugin-prettier 和 eslint-config-prettier
import eslintPluginPrettierRecommended from 'eslint-plugin-prettier/recommended'
export default defineConfig([
// 其它配置
...
// Prettier 扩展插件
eslintPluginPrettierRecommended
])
7. Husky (Git钩子工具)
// package.json
{
"husky": {
"hooks": {
"pre-commit": "lint-staged",
"commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
}
}
}
功能说明:
- Git 钩子管理工具
- 在提交前自动运行代码检查
- 确保提交信息符合规范
- 防止不合格代码进入仓库
使用方法:
# 安装husky
npm install husky --save-dev
# 初始化husky
npx husky install
8. lint-staged (增量检查)
// package.json
{
"lint-staged": {
"*.{js,jsx,vue}": [
"eslint --fix",
"prettier --write"
]
}
}
# .husky/pre-commit
npx --no-install -- lint-staged
功能说明:
- 只检查暂存区的文件
- 提高代码检查效率
- 与 Husky 配合实现提交前检查
- 支持并行执行多个任务
使用方法:
# 安装lint-staged
npm install lint-staged --save-dev
9、生产环境禁用console语句插件vite-plugin-remove-console
1、安装插件
pnpm add vite-plugin-remove-console -D
2、修改vite.config.js
import { defineConfig } from 'vite'
import uni from '@dcloudio/vite-plugin-uni'
import removeConsole from 'vite-plugin-remove-console'
export default defineConfig({
plugins: [
uni(),
removeConsole(), // 移除所有 console 语句
],
})
3、按需移除
removeConsole({
includes: ['log', 'warn', 'error'], // 只移除 console.log、console.warn、console.error
// external: ['error', 'warn'] //保留
})
更多推荐



所有评论(0)