当前位置: 首页 > news >正文

uniapp创建vue3+ts+pinia+sass项目

1.执行命令行创建,暂时在Hbuildx中无法创建ts项目

npx degit dcloudio/uni-preset-vue#vite-ts my-uniapp-project

注意:创建失败时,注意VPN的问题。

2.安装依赖

npm install

3.安装sass 

npm install -D sass sass-loader

4. 安装 @uni-helper/uni-types(增加ts支持)

npm install @uni-helper/uni-types

注意:此时可能会出现问题,例如:
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: uni-preset-vue@0.0.0
npm ERR! Found: typescript@4.9.5
npm ERR! node_modules/typescript
npm ERR!   dev typescript@"^4.9.4" from the root project
npm ERR!
npm ERR! peer typescript@"^5.0.0" from @uni-helper/uni-types@1.0.0-alpha.6
npm ERR! node_modules/@uni-helper/uni-types
npm ERR!   @uni-helper/uni-types@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR!
npm ERR! For a full report see:
npm ERR! C:\Users\Administrator\AppData\Local\npm-cache\_logs\2025-07-25T02_27_05_562Z-eresolve-report.txt
npm ERR! A complete log of this run can be found in: C:\Users\Administrator\AppData\Local\npm-cache\_logs\2025-07-25T02_27_05_562Z-debug-0.log

 这个错误是因为 npm 依赖冲突,具体原因是 @uni-helper/uni-types@1.0.0-alpha.6 需要 TypeScript 5.0+,但你的项目当前使用的是 TypeScript 4.9.5。只需更新ts后再安装即可
更新ts:

npm install typescript@latest --save-dev

5. 配置tsconfigjson 

{//"extends": "@vue/tsconfig/tsconfig.json","compilerOptions": {"module": "es2020", // 或 "es2022", "esnext", "node16", "node18""target": "esnext", // 建议与 module 保持同步"moduleResolution": "node", // 确保模块解析策略正确"sourceMap": true,"baseUrl": ".","paths": {"@/*": ["./src/*"]},"lib": ["esnext","dom"],"types": ["@dcloudio/types","vue"]},"vueCompilerOptions": {"plugins": ["@uni-helper/uni-types/volar-plugin"]},"include": ["src/**/*.ts","src/**/*.d.ts","src/**/*.tsx","src/**/*.vue"]
}

6.配置环境,在根目录文件下创建.env,.env.production,.env.development,.env.test

# Node 运行环境
NODE_ENV=development# 后端接口地址
VITE_APP_BASE_URL=https://xxx.xxxx.com# oss资源地址
VITE_APP_OSS_URL=https://xxx.com# 接口基础地址
VITE_APP_BASE_API=/app-api# 自定义环境标识
VITE_APP_ENV=development

7.安装pinia(其中pinia-plugin-persistedstate 是一个为 Pinia 设计的插件,用于持久化存储 Pinia 的状态(state),使其在页面刷新、浏览器关闭后重新打开时能自动恢复数据。它类似于 Vuex 的持久化插件,但专门适配 Pinia 的响应式架构。
注意:如果安装失败,可能是vue版本不够最新的pinia,只需更新vue为新增vue3版本即可

npm i pinia
npm i pinia-plugin-persistedstate

8.创建src/store/index.ts

import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'// 创建 pinia 实例
const pinia = createPinia()// 使用持久化插件
pinia.use(piniaPluginPersistedstate)export default pinia

9.配置main.ts

import { createSSRApp } from "vue";
import App from "./App.vue";
import pinia from './store';
export function createApp() {const app = createSSRApp(App);app.use(pinia);return {app,};
}

10.此时vue可能会提示找不到,在src下新建文件shims-vue.d.ts

// src/shims-vue.d.ts
declare module '*.vue' {/* import { DefineComponent } from 'vue'const component: DefineComponent<{}, {}, any>export default component */
}

11.封装请求,新建utils/request/index.ts

npm i luch-request
import Request from 'luch-request';
import type { RequestFunction, ErrorResponse, RequestConfig } from './types';const baseUrl = import.meta.env.VITE_API_BASE_URL;
const baseApi = import.meta.env.VITE_API_BASE_API;const options = {// 显示操作成功消息 默认不显示showSuccess: false,// 成功提醒 默认使用后端返回值successMsg: '',// 显示失败消息 默认显示showError: true,// 失败提醒 默认使用后端返回信息errorMsg: '',// 显示请求时loading模态框 默认不显示showLoading: false,// loading提醒文字// 需要授权才能请求 默认放开auth: false,
};// 创建请求实例
const httpRequest = new Request({baseURL: `${baseUrl}${baseApi}`,timeout: 10000,header: {Accept: 'text/json','Content-Type': 'application/json;charset=UTF-8',},custom: options,
});// 请求拦截器
httpRequest.interceptors.request.use(config => {// 获取登录状态const isLoggedIn = !!uni.getStorageSync('token');if (config?.custom?.auth && !isLoggedIn) {// 未登录,弹出登录弹窗return Promise.reject();}// 在发送请求之前做些什么const token = uni.getStorageSync('token');if (token) {config.header = config.header || {};config.header.Authorization = `Bearer ${token}`;}return config;},error => {return Promise.reject(error);},
);// 响应拦截器
httpRequest.interceptors.response.use(response => {// 对响应数据做点什么return response;},error => {// 处理错误const { statusCode, data } = error as ErrorResponse;switch (statusCode) {case 401:// 未授权,跳转到登录页uni.navigateTo({url: '/pages/login/index',});break;case 403:// 权限不足,显示自定义弹窗uni.showModal({title: '提示',content: data.message || '您没有权限执行此操作',showCancel: false,});break;case 500:// 服务器错误,显示系统提示uni.showToast({title: '服务器错误,请稍后重试',icon: 'none',});break;default:// 其他错误,显示错误信息uni.showToast({title: data.message || '请求失败',icon: 'none',});}return Promise.reject(error);},
);const request: RequestFunction = config => {return httpRequest.middleware(config);
};export { request };

types.ts:

import type { HttpRequestConfig, HttpTask, HttpData } from 'luch-request';// 响应数据基础接口
export interface BaseResponse<T = any> {code: number;data: T;message: string;
}// 请求配置扩展
export type RequestConfig<T = any> = Omit<HttpRequestConfig<HttpTask>, 'data'> & {data?: T extends HttpData ? T : HttpData;
};// HTTP 请求方法类型
export type HttpMethod =| 'GET'| 'POST'| 'PUT'| 'DELETE'| 'OPTIONS'| 'HEAD'| 'TRACE'| 'CONNECT';// 请求函数类型
export type RequestFunction = <T = any, R = any>(config: RequestConfig<T>,
) => Promise<BaseResponse<R>>;// 错误响应类型
export interface ErrorResponse {statusCode: number;data: {code: number;message: string;};
}// 请求实例配置接口
export interface RequestInstanceConfig {baseURL: string;timeout: number;header: Record<string, string>;
}export interface RequestError {statusCode: number;data: any;config: HttpRequestConfig;errMsg: string;
}export type ErrorMiddleware = (error: RequestError,next: (error: RequestError) => void,
) => Promise<void> | void;// 请求实例类型

http://www.dtcms.com/a/297750.html

相关文章:

  • 2025年RISC-V中国峰会 主要内容
  • 绘图库 Matplotlib Search
  • RISC-V VP、Gem5、Spike
  • 恋爱时间倒计时网页设计与实现方案
  • 借助Aspose.HTML控件,在 Python 中将 SVG 转换为 PDF
  • Vue nextTick
  • 基于超176k铭文数据,谷歌DeepMind发布Aeneas,首次实现古罗马铭文的任意长度修复
  • MySQL存储引擎深度解析与实战指南
  • Java面试题及详细答案120道之(001-020)
  • JAVA_FIFTEEN_异常
  • LeetCode 233:数字 1 的个数
  • Zero-Shot TrackingT0:对象分割+运动感知记——当“切万物”武士学会运动记忆,目标跟踪稳如老狗
  • 力扣面试150题--寻找旋转排序数组中的最小值
  • 互联网金融项目实战(大数据Hadoop hive)
  • 代码随想录算法训练营第五十三天|图论part4
  • Hive【Hive架构及工作原理】
  • Hive-vscode-snippets
  • 微信小程序文件下载与预览功能实现详解
  • nacos安装
  • SpringBoot配置多数据源多数据库
  • Androidstudio 上传当前module 或本地jar包到maven服务器。
  • 线性代数 上
  • Java 大视界 -- 基于 Java 的大数据分布式存储在工业互联网数据管理与边缘计算协同中的创新实践(364)
  • 从入门到进阶:JavaScript 学习之路与实战技巧
  • Nginx 安装与 HTTPS 配置指南:使用 OpenSSL 搭建安全 Web 服务器
  • Django集成Swagger全指南:两种实现方案详解
  • 探索 MyBatis-Plus
  • 智慧灯杆:不止于照明,塔能科技的城市感知网络野心
  • 解码3D格式转换
  • 多智能体(Multi-agent)策略模式:思维链CoT和ReAct