最新Vite+ts+vue3+pinna项目搭建全步骤及其踩坑!

963 阅读4分钟

手把手搭建一个vite+vue3+pinia+ts的项目

1. 开始

搭建项目需要 NodeJs 版本 >- 15.0.0

使用npm

   npm init vue@latest

该命令将安装并执行官方的 Vue 项目脚手架工具create-vue。您将看到一些可选功能的提示,

Project name: … <your-project-name>  // 项目名称Add TypeScript? … No / Yes   // 是否需要 Ts 支持, YesAdd JSX Support? … No / Yes  // 是否需要JSX 语法支持 YesAdd Vue Router for Single Page Application development? … No / Yes // 是否为单页应用添加Vue-Router YesAdd Pinia for state management? … No / Yes // 是否使用 pinia   YesAdd Vitest for Unit testing? … No / Yes // 是否添加单元测试 NoAdd Cypress for both Unit and End-to-End testing? … No / Yes  // 是否给单元测试添加 cypress  NoAdd ESLint for code quality? … No / Yes  // 添加 eslint 校验  YesAdd Prettier for code formatting? … No / Yes  // 添加prettier代码格式化 Yes

Scaffolding project in ./<your-project-name>...
Done.

启动开发服务器:

> cd <your-project-name>
> npm install
> npm run dev

注意事项: 当在运行时,发现以下这种错误的时候,

error when starting dev server:

Error: Cannot find module 'node:path' or 'node:url'

检查你的node版本,更新到>16.0.0 以上,即可修复。原因:因为vite3.0+ 版本导致的。

启动成功 image.png

2. 安装element-plus

推荐使用npm方式进行安装

> npm install element-plus -S

用法

完整引入

如果你对打包后的文件大小不是很在乎,那么使用完整导入会更方便。

// main.ts
import { createApp } from 'vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import App from './App.vue'

const app = createApp(App)

app.use(ElementPlus)
app.mount('#app')

Volar 支持

如果您使用 Volar,请在 tsconfig.json 中通过 compilerOptions.type 指定全局组件类型。

// tsconfig.json
{
  "compilerOptions": {
    // ...
    "types": ["element-plus/global"]
  }
}

如需按需导入或者其他方式,请参考官网:按需导入

Tips: 如果你是使用Vscode,且之前安装过Vetur, 请禁用该插件。

使用Vue Language Features (Volar)这个插件

原因:Vetur 是针对Vue2语法的插件,Volar 是针对于Vue3的语法插件

3. 使用 scss 预编译器

由于 Vite 的目标仅为现代浏览器,因此建议使用原生 CSS 变量和实现 CSSWG 草案的 PostCSS 插件(例如 postcss-nesting)来编写简单的、符合未来标准的 CSS。

话虽如此,但 Vite 也同时提供了对 .scss.sass.less.styl 和 .stylus 文件的内置支持。没有必要为它们安装特定的 Vite 插件,但必须安装相应的预处理器依赖:

# .scss and .sass
npm install -D sass

# .less
npm install -D less

# .styl and .stylus
npm install -D stylus

安装成功后,直接可以使用。

<style scoped lang="scss">
  .wrapper {
    min-height: 100vh;
    width: 100%;
    .el-aside {
      background: #f5f5f5;
      text-align: center;
    }
    .el-header {
      background: #c6e2ff;
    }
  }
</style>

4. 安装postcss兼容不同浏览器

  1. 使用npm安装 autoprefixer 插件
> npm install autoprefixer -D
  1. 在package.json中添加以下代码
...
"browserslist": [
   "> 1%",
   "last 2 versions",
   "not ie <= 8"
]
  1. 在项目根目录创建.postcssrc.js文件
module.exports = {
  "plugins": {
    // to edit target browsers: use "browserslist" field in package.json
    "autoprefixer": {}
  }
}

在看到样式在有不同浏览器的前缀,即为成功。

image.png

5. 安装axios

使用npm 安装

> npm install -S axios

在src下创建 utils/request.ts 和 utils/requestTypes.ts

import axios from 'axios'
import { requestConfig, BaseRequest, ResultModel } from './requestTypes'

const service = axios.create(new requestConfig())


// 添加请求拦截器
service.interceptors.request.use(
  function (config:any) {
    // 请求之前附带token信息
    config.headers.Authorization = `Bearer ` + 'xxxx'
    
    return config;
  },
  function (error) {
    // 对请求错误做些什么,提示错误信息
    return Promise.reject(error)
  },
)


// 添加响应拦截器
service.interceptors.response.use(
  function (response) {
    // 对响应数据做点什么,提示成功信息
    let res = <ResultModel>response.data
    return res
  },
  function (error: any) {
    // 对响应错误做点什么,提示错误信息
    return Promise.reject(error)
  },
)

requestTypes.ts

/**
 * 请求结果
 */
 export class ResultModel {
  // 结果集
  data?: object
  // 状态码
  code?: number
  // 请求消息
  message?: string
}

/**
 * 基础请求对象
 */
export class BaseRequest {
  public url: string
  public data: object | any

  constructor(url: string, data: object = {}) {
    this.url = url
    this.data = data
  }
}

/**
 * 请求配置
 */
export class requestConfig {
  // `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。
  public readonly baseURL: string
  // 如果请求话费了超过 `timeout` 的时间,请求将被中断
  public readonly timeout: number

  constructor() {
    this.baseURL = import.meta.env.VITE_HOST_API
    this.timeout = 3000
  }
}

6. 环境变量

关于 import.meta.env.VITE_HOST_API 详细可见Vite

Vite 在一个特殊的 import.meta.env 对象上暴露环境变量。这里有一些在所有情况下都可以使用的内建变量:

  • import.meta.env.MODE: {string} 应用运行的模式
  • import.meta.env.BASE_URL: {string} 部署应用时的基本 URL。他由base 配置项决定。
  • import.meta.env.PROD: {boolean} 应用是否运行在生产环境。
  • import.meta.env.DEV: {boolean} 应用是否运行在开发环境 (永远与 import.meta.env.PROD相反)。
  • import.meta.env.SSR: {boolean} 应用是否运行在 server 上。

默认情况下,Vite 在 [vite/client.d.ts] 中为 import.meta.env 提供了类型定义。随着在 .env[mode] 文件中自定义了越来越多的环境变量,你可能想要在代码中获取这些以 VITE_ 为前缀的用户自定义环境变量的 TypeScript 智能提示。

要想做到这一点,你可以在 src 目录下创建一个 env.d.ts 文件,接着按下面这样增加 ImportMetaEnv 的定义:

/// <reference types="vite/client" />

interface ImportMetaEnv {
  readonly VITE_APP_TITLE: string
  // 更多环境变量...
}

interface ImportMeta {
  readonly env: ImportMetaEnv
}

记得在package.json文件中的 scripts 执行命令中添加 --mode dev

 "scripts": {
    "dev": "vite --mode dev", // 这里
    "build": "run-p type-check build-only",
    "preview": "vite preview --port 4173",
    "build-only": "vite build",
    "type-check": "vue-tsc --noEmit",
    "lint": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs,.ts,.tsx,.cts,.mts --fix --ignore-path .gitignore"
  },

7. 使用pinia状态管理工具

使用 pinia 几乎与 vuex 没有区别

actions 触发方法

getters 计算属性 可直接调用使用 「推荐」

pinia 配置

image.png

pinia 使用

image.png

Tips: 如果有小伙伴遇到以下内容的错误

image.png

在项目的根目录创建一个 shims.d.ts 文件

declare module "*.vue" {
  import { defineComponent } from "vue";
  // const Component: ReturnType<typeof defineComponent>;
  const Component: defineComponent<{}, {}, any>
  export default Component;
}

并且在tsconfig.json中添加该配置

{
  "extends": "@vue/tsconfig/tsconfig.web.json",
  "include": ["env.d.ts", "src/**/*", "src/**/*.vue", "shims.d.ts"], // 这里
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["./src/*"]
    }
  },

  "references": [
    {
      "path": "./tsconfig.config.json"
    }
  ]
}

8. 项目模板地址

传送门: vue3-ts-vite-pinia

创作不易,哥哥姐姐们点个关注吧。

扫码关注微信公众号,每日更新。感谢!

image.png