前端项目构建 vite2 vue3 ts Vuex4 VueRouter4 Element-plus axios

项目构建

vite2 vue3 ts Vuex VueRouter Element-plus axios

vscode

#初始化项目
npm init vite@latest

#or

yarn create vite
#Need to install the following packages:
#  create-vite@latest
#Ok to proceed? (y) y
#√ Project name: ... shop-admin
#√ Select a framework: » vue
#√ Select a variant: » vue-ts
#Scaffolding project in E:\vue_project\shop-admin...
#Done. Now run:

#进入项目文件夹
cd shop-admin
#使用vscode打开项目
code .
#打开终端  安装依赖包
  npm install
  npm run dev
	
#or
 
  yarn
  yarn dev
	
-----------------------------------------------
1.安装eslint代码检测插件
npm install eslint --save-dev

# or

yarn add eslint --dev
2.初始化ESlint配置
npm init @eslint/config

# or

yarn create @eslint/config


-----------------------------------------------
? How would you like to use ESLint? ...
  To check syntax only
  To check syntax and find problems
> To check syntax, find problems, and enforce code style
-----------------------------------------------
? What type of modules does your project use? ...
> JavaScript modules (import/export)
  CommonJS (require/exports)
  None of these
-----------------------------------------------
? Which framework does your project use? ...
  React
> Vue.js
  None of these
-----------------------------------------------
? Does your project use TypeScript? » No / Yes Yes
-----------------------------------------------
? Where does your code run? ...  (Press <space> to select, <a> to toggle all, <i> to invert selection)
√ Browser
  Node
-----------------------------------------------
? How would you like to define a style for your project? ...
> Use a popular style guide
  Answer questions about your style
-----------------------------------------------
? Which style guide do you want to follow? ...
  Airbnb: https://github.com/airbnb/javascript
> Standard: https://github.com/standard/standard
  Google: https://github.com/google/eslint-config-google
  XO: https://github.com/xojs/eslint-config-xo
-----------------------------------------------
? What format do you want your config file to be in? ...
> JavaScript
  YAML
  JSON
-----------------------------------------------
? The style guide "standard" requires eslint@^7.12.1. You are currently using eslint@8.13.0.
  Do you want to downgrade? » No / Yes  Yes
-----------------------------------------------
eslint-plugin-vue@latest @typescript-eslint/eslint-plugin@latest eslint-config-standard@latest eslint@^7.12.1 eslint-plugin-import@^2.22.1 eslint-plugin-node@^11.1.0 eslint-plugin-promise@^4.2.1 || ^5.0.0 @typescript-eslint/parser@latest
? Would you like to install them now with npm? » No / Yes  Yes
4.npm script 中添加验证脚本package.json
 "scripts": {
 	...
    "lint": "eslint ./src/**/*.{js,jsx,vue,ts,tsx} --fix"
  },
}
5. .eslintrc.js eslint验证规则修改为vue3
  • node_modules\eslint-plugin-vue\lib\configs\vue3-strongly-recommended.js
  • 参考官网

extends: [
    'plugin:vue/essential', 
    ]
    
# 修改为    

extends: [
	'plugin:vue/vue3-strongly-recommended',
	]

eslint 配置 git commit hook

#git初始化
git init

#安装插件
npx mrm@2 lint-staged
  • package.json 修改lint-staged
"lint-staged": {
    "*.{js,jsx,vue,ts,tsx}": "npm run lint"  
  }
 #or
 "lint-staged": {
    "*.{js,jsx,vue,ts,tsx}": "yarn lint"  
  }
#删除项目文件夹中的 6
在开发和构建中进行代码规范校验
	#install
	npm install vite-plugin-eslint --save-dev
	# or
	yarn add vite-plugin-eslint --dev
  • 修改vite.config.ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import eslintPlugin from 'vite-plugin-eslint'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue(),
    eslintPlugin({
      // 配置选项
      cache: false // 禁用eslint缓存
    })]
})

git commit规范
# For Windows:
npm install --save-dev @commitlint/config-conventional @commitlint/cli

# Configure commitlint to use conventional config
#创建commitlint.config.js
#文件内容(下面一行)
module.exports = {extends: ['@commitlint/config-conventional']}

  • husky配置
# 因为前面 lint-staged 使用的npx命令 并且已经安装了husky 所以这里也需要使用 npx
# Install Husky v6
npm install husky --save-dev

# Activate hooks
npx husky install

# Add hook
npx husky add .husky/commit-msg "npx --no -- commitlint --edit $1"
vue3中setup语法糖 eslint校验出现问题
module.exports = {
  env: {
    'vue/setup-compiler-macros': true
  }
}
配置转换JSX和TSX
 npm i -D @vitejs/plugin-vue-jsx
  • Provides Vue 3 JSX & TSX support with HMR.
  • vite.config.js中添加
// vite.config.ts
import vueJsx from '@vitejs/plugin-vue-jsx'

export default {
  plugins: [
    vueJsx({
      // options are passed on to @vue/babel-plugin-jsx
    })
  ]
}
初始化VueRouter
npm install vue-router@4

初始化 Vuex

npm install vuex@next --save
#or
yarn add vuex@next --save
//Vuex 没有为 this.$store 属性提供开箱即用的类型声明。如果你要使用 TypeScript,首先需要声明自定义的模块补充(module augmentation)。
//为此,需要在项目文件夹中添加一个声明文件来声明 Vue 的自定义类型 ComponentCustomProperties

// src/vuex.d.ts
import { ComponentCustomProperties } from 'vue'
import { Store } from 'vuex'

declare module '@vue/runtime-core' {
  // 声明自己的 store state
  interface State {
    count: number
  }

  // 为 `this.$store` 提供类型声明
  interface ComponentCustomProperties {
    $store: Store<State>
  }
}
//引入 InjectionKey 并将其传入 useStore 使用过的任何地方,很快就会成为一项重复性的工作。为了简化问题,可以定义自己的组合式函数来检索类型化的 store :
-----------------------------------------------
// store.ts (store/index.ts)
import { InjectionKey } from 'vue'
import { createStore, useStore as baseUseStore, Store } from 'vuex'

export interface State {
  count: number
}

export const key: InjectionKey<Store<State>> = Symbol()

export const store = createStore<State>({
  state: {
    count: 0
  }
})

// 定义自己的 `useStore` 组合式函数
export function useStore () {
  return baseUseStore(key)
}
-----------------------------------------------
//现在,通过引入自定义的组合式函数,不用提供 injection key 和类型声明就可以直接得到类型化的 store:
-----------------------------------------------
// vue 组件
import { useStore } from './store'

export default {
  setup () {
    const store = useStore()

    store.state.count // 类型为 number
  }
}
配置vite中模块别名
npm i -D @types/node
  • vite.config.ts中添加
import {join} from 'path'


export default defineConfig({
 resolve: {
    alias: {
      '@': join(__dirname, 'src')
    }
  }
  • tsconfig.json中加入paths
 "compilerOptions": {
 ...
    "paths": {
      "@/*":[
        "./src/*"
      ]
    }
  },
CSS样式管理
# .scss and .sass install
npm install -D sass
  • src下创建 style文件夹 创建

    文件名说明
    variables.scss全局Sass变量
    mixin.scss全局mixin
    common.scss全局公共样式
    transition.scss全局过度动画样式
    index.scss组织统一导出
    //variables.scss  全局Sass变量
    $color: red
    
    //index.scss 组织统一导出
    @import "./common.scss";
    @import "./mixin.scss";
    @import "./transition.scss";
    @import "./variables.scss";
    
    
    //	main.ts	中导入index.scss
    // 加载全局样式
    import '@/style/index.scss'
    
  • 指定传递给 CSS 预处理器的选项

// vite.config.ts 加入
  css: {
    preprocessorOptions: {
      scss: {
        additionalData: '@import "@/style/variables.scss";'
      }
    }
  }
})
基于axios封装请求模块
  • 安装axios:

    npm install axios
    
    #or
    
    yarn add axios
    
  • 禁用api目录下的eslint驼峰命名验证

     overrides: [
        {
          files: ['src/api/**/*.ts'],
          rules: {
            camelcase: 'off'
          }
        }
      ]
    }
    
  • 创建/src/utils/request.ts

    //src/utils/request.ts
    import axios, { AxiosRequestConfig } from 'axios'
    
    // request 不支持泛型
    // request.get 、post、 put支持响应数据泛型
    
    const request = axios.create({
      baseURL: 'https://www.fastmock.site/mock/5f5c83c74506389e42f1b7d88fad82f5/charles'
    })
    
    // 请求拦截器
    request.interceptors.request.use(function (config) {
      // 统一设置用户身份 token
      return config
    }, function (error) {
      // Do something with request error
      return Promise.reject(error)
    })
    
    // 响应拦截器
    request.interceptors.response.use(function (response) {
      // 统一处理接口响应错误 比如 toke过期无效 服务器端异常等
      return response
    }, function (error) {
      // Any status codes that falls outside the range of 2xx cause this function to trigger
      // Do something with response error
      return Promise.reject(error)
    })
    
    export default <T = any>(config: AxiosRequestConfig) => {
      return request(config).then(res => {
        return res.data.data as T
      })
    }
    
    
  • 创建接口类型模块/src/api/types/common.ts

    //src/api/types/common.ts
    export interface ILoginInfo {
     logo_square: string;
      logo_rectangle: string;
      login_log: string;
      slide: string[];
    }
    
  • 创建/src/api/common.ts

    //src/api/common.ts
    /***
     * 公共基础接口封装
     */
    
    //  {
    //     "data": {
    //       "slide": [
    //         "bb",
    //         "bb"
    //       ],
    //       "logo_square": "aa",
    //       "logo_rectangle": "bb",
    //       "login_log": "cc"
    //     },
    //     "msg": "ok",
    //     "status": 200
    //   }
    
    import request from '@/utils/request'
    import type { ILoginInfo } from './types/common'
    
    export const getLoginInfo = () => {
      return request<ILoginInfo>({
        method: 'GET',
        url: '/login/info'
      })
    }
    
    
环境变量和模式
  • vite-环境变量和模式

  • 项目根目录创建以下文件

    .env                # 所有情况下都会加载的环境变量
    .env.local          # 所有情况下都会加载的环境变量,但会被 git 忽略
    .env.development    # 开发模式下加载的环境变量
    .env.production     # 生产模式下加载的环境变量
    
  • .env.development 中创建一个环境变量

    # 开发模式下加载的环境变量
    VITE_API_BASEURL = https://www.fastmock.site/mock/5f5c83c74506389e42f1b7d88fad82f5/charles
    
  • src 目录下创建一个 env.d.ts 声明环境变量的类型

    // eslint-disable-next-line no-unused-vars
    interface ImportMetaEnv {
      readonly VITE_API_BASEURL: string
      // 更多环境变量...
    }
    
  • 修改/src/utils/request.ts 引用环境变量

    const request = axios.create({
      baseURL: import.meta.env.VITE_API_BASEURL
    })
    
跨域问题 CORS

解决方案:

开发环境生产环境
在服务端配置CORS在服务端配置CORS
配置开发服务器代理,比如 vite-server.proxy配置生产服务器代理,比如nginx
Element-plus
  • element-plus
    npm install element-plus --save
    
    # or
    
    yarn add element-plus
    
    • 创建/src/plugins/element-plus.ts
    // src/plugins/element-plus.ts
    import ElementPlus from 'element-plus'
    import 'element-plus/dist/index.css'
    import { App } from 'vue'
    
    export default {
      install (app: App) {
        app.use(ElementPlus, { size: 'small', zIndex: 2000 })
      }
    }
    
    
  • main.ts中引入
    import elementPlus from './plugins/element-plus'
    
    createApp(App)
      .use(router)
      .use(store, key)
      .use(elementPlus)
      .mount('#app')
    
    
  • 国际化-全局配置
  • 修改App.vue
    <template>
      <el-config-provider :locale="locale">
        <router-view />
      </el-config-provider>
    </template>
    
    <script setup lang="ts">
    import locale from 'element-plus/lib/locale/lang/zh-cn'
    </script>
    
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vite是一个用于快速构建现代化的Web项目构建工具,它专注于开发阶段的快速热重载,并使用ES模块作为原生的开发模式。Vue3是Vue.js的最新版本,它在性能、开发体验和可维护性上都有所提升。 针对你提到的具体的库和框架: - Vue RouterVue.js官方的路由管理器,用于实现页面之间的导航和路由控制。你可以通过npm安装vue-router,并在项目中进行配置和使用。 - Pinia是Vue.js的状态管理库,它提供了一种简单而强大的方式来管理应用程序的状态。你可以集成Pinia到你的Vue项目中,以便更好地组织和共享你的应用程序状态。 - Axios是一个基于Promise的HTTP客户端,用于通过网络发送异步请求。你可以使用Axios来处理与服务器的通信,并获取数据来更新你的Vue应用程序。 - Element Plus是一套基于Vue3的组件库,包含了丰富的UI组件,可以帮助你快速搭建漂亮的用户界面。你可以在项目中安装和使用Element Plus来实现各种交互效果和用户界面。 如果你想使用Vite、Vue3和以上提到的库和框架来创建一个项目,你可以按照以下步骤进行: 1. 安装Vite:通过npm全局安装Vite,然后使用Vite命令初始化一个新的项目。 2. 配置Vite:根据你的项目需求,在Vite的配置文件中添加Vue Router、Pinia、AxiosElement Plus的相关配置。 3. 安装和配置Vue Router:通过npm安装Vue Router,并在项目中配置和使用Vue Router来管理应用程序的路由。 4. 集成Pinia:通过npm安装Pinia,并在项目中引入和配置Pinia,以便在应用程序中使用Pinia来管理状态。 5. 使用Axios:通过npm安装Axios,并在项目中引入和配置Axios,以便进行网络请求和数据获取。 6. 引入Element Plus:通过npm安装Element Plus,并在项目中按需引入和使用Element Plus的组件,以搭建漂亮的用户界面。 希望以上信息对你有帮助,祝你在使用Vite、Vue3和这些库和框架时取得成功!<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [vite-vue-ts精简模版集成pinia+svg+router+@src](https://download.csdn.net/download/ldy889/85018930)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [vite+vue3+ts+vue-router+pinia+axios+element-plus](https://blog.csdn.net/zy_080400/article/details/127125359)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值