vite + vue3 + ts搭建項目


使用 Vite 快速搭建

Npm
npm init @vitejs/app`

Yarn
yarn create @vitejs/app

選擇vue- vue-ts

安裝依賴

npm install

啟動項目

npm run dev

修改 Vite 配置文件

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      '@': resolve('./src')
    }
  },
  base: './', // 打包路徑
  server: {
    port: 4000, // 服務端口號
    open: true, // 服務啟動時是否自動打開瀏覽器
    cors: true // 允許跨域
  }
})

配置文件
如果使用 ​​TS​​ ,則需要先安裝類型聲明文件。

npm install --save-dev @types/node

ts

/*
 * @Author: your name
 * @Date: 2021-09-04 08:39:20
 * @LastEditTime: 2021-09-04 09:07:30
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \vue-vite-blog\src\env.d.ts
 */
/// <reference types="vite/client" />
declare module '*.vue' {
  import { DefineComponent } from 'vue'
  // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/ban-types
  const component: DefineComponent<{}, {}, any>
  export default component
}
// declare module 'axios';
// declare module 'qs';

集成路由
安裝

npm i vue-router@4

創建 ​​src/router/index.ts​​ 文件

/*
 * @Author: your name
 * @Date: 2021-09-04 08:43:27
 * @LastEditTime: 2021-09-04 08:49:29
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \vue-vite-blog\src\router\index.ts
 */
import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/home',
    name: 'Home',
    component: () => import(/* webpackChunkName: "Home" */ '../views/Home/Home.vue')
  },
  { path: '/', redirect: { name: 'Home' } }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

export default router

main.ts 文件中掛載

import { createApp } from 'vue'
import App from '@/App.vue'

import router from '@/router/index'
createApp(App).use(router).mount('#app')

集成Vuex

​npm i vuex@next​​
創建 ​​src/store/index.ts​​ 文件
/*

* @Author: your name
* @Date: 2020-12-07 18:59:37
* @LastEditTime: 2021-08-09 09:57:17
* @LastEditors: Please set LastEditors
* @Description: In User Settings Edit
* @FilePath: \blogs-s\src\store\index.ts
*/
import {
createStore
} from 'vuex'

 
         

export default createStore({
state: {

 
         

token: "test",
//設置頁面是否新窗口打開
SetPage: false
},

 
         

mutations: {

 
         

},
actions: {},
modules: {}
})

 

main.ts 文件掛載

import { createApp } from 'vue'
import App from '@/App.vue'

import router from '@/router/index'
import store from '@/store/index'

createApp(App).use(router).use(store).mount('#app')

集成 Axios

npm i axios​​
配置 ​​Axios​​

/*
 * @Author: Axios封裝
 * @Date: 2020-12-08 10:39:03
 * @LastEditTime: 2021-09-04 09:04:19
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \blogs-s\src\api\index.ts
 */
import axios from 'axios'
import qs from "qs";
import store from "../store/index";
import router from '../router';
//'http://129.204.92.64:8081/' 騰訊服務器
// axios.defaults.baseURL = 'https://localhost:44367/',
axios.defaults.baseURL = process.env.VUE_APP_API_URL,
  axios.defaults.timeout = 12000;
// axios.defaults.headers.common['token'] =  AUTH_TOKEN
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';
axios.defaults.headers.post["Access-Control-Allow-Origin-Type"] = "*"; // 允許跨域

axios.interceptors.request.use(function (config: any) {

  // 在發送請求之前做某件事
  if (
    config.method === "post" ||
    config.method === "put" ||
    config.method === "delete"
  ) {
    // 序列化
    config.data = qs.parse(config.data);
    // console.log("qs:" + config.data);
  }
  // 若是有做鑒權token , 就給頭部帶上token
  if (store.state.token) {
    config.headers.Authorization = store.state.token;
    // console.log("token:" + store.state.token);
  }
  return config;
}, (error: { data: { error: { message: any; }; }; }) => {
  // Message({
  //   //  餓了么的消息彈窗組件,類似toast
  //   showClose: true,
  //   message: error,
  //   type: "error.data.error.message"
  // });
  return Promise.reject(error.data.error.message);
})

axios.interceptors.response.use(function (config: any) {

  if (config.status === 200 || config.status === 204) {
    return Promise.resolve(config);
  } else {
    return Promise.reject(config);
  }

  // return config;
},
  function (error: { response: { status: any; }; }) {
    // return Promise.reject(error)

    if (error.response.status) {
      switch (error.response.status) {
        // 401: 未登錄
        // 未登錄則跳轉登錄頁面,並攜帶當前頁面的路徑
        // 在登錄成功后返回當前頁面,這一步需要在登錄頁操作。                
        case 401:
          router.replace({
            path: '/login',
            query: {
              // redirect: router.currentRoute.fullPath
            }
          });
          break;
        // 403 token過期
        // 登錄過期對用戶進行提示
        // 清除本地token和清空vuex中token對象
        // 跳轉登錄頁面                
        case 403:
          // Toast({
          //   message: '登錄過期,請重新登錄',
          //   duration: 1000,
          //   forbidClick: true
          // });
          // 清除token
          store.dispatch('FedLogOut').then(() => {
            // 跳轉登錄頁面,並將要瀏覽的頁面fullPath傳過去,登錄成功后跳轉需要訪問的頁面 
            router.replace({
              path: '/login',
              query: {
                // redirect: router.currentRoute.fullPath
              }
            })
          })
          break;

        // 404請求不存在
        case 404:
          // Toast({
          //   message: '網絡請求不存在',
          //   duration: 1500,
          //   forbidClick: true
          // });
          break;
        // 其他錯誤,直接拋出錯誤提示
        default:
        // Toast({
        //   message: error.response.data.message,
        //   duration: 1500,
        //   forbidClick: true
        // });
      }
      return Promise.reject(error.response);
    } else {
      // 處理斷網的情況
      // eg:請求超時或斷網時,更新state的network狀態
      // network狀態在app.vue中控制着一個全局的斷網提示組件的顯示隱藏
      // 關於斷網組件中的刷新重新獲取數據,會在斷網組件中說明
      store.commit('changeNetwork', false);
    }
  }
)

export default axios

掛載

import axios from './api/axios'
// 全局ctx(this) 上掛載 $axios
app.config.globalProperties.$api = axios

集成CSS預編譯器

npm i sass -D

安裝 Tailwind CSS

npm install -D tailwindcss@npm:@tailwindcss/postcss7-compat @tailwindcss/postcss7-compat postcss@^7 autoprefixer@^9

創建配置文件

npx tailwindcss init -p

// tailwind.config.js
/*
* @Author: your name
* @Date: 2020-12-08 09:43:09
* @LastEditTime: 2021-09-02 08:54:26
* @LastEditors: Please set LastEditors
* @Description: In User Settings Edit
* @FilePath: \blogs-s\tailwind.config.js
*/
module.exports = {
// purge: ['./src/**/*.{vue,js,ts,jsx,tsx}'], //刪除未使用的CSS
purge: {
enabled: true,
content: ['./src/**/*.{vue,js,ts,jsx,tsx}'],
},
darkMode: false, // or 'media' or 'class'
theme: {
screens: {

'cx': {
'max': '575px'
},
'xp': {
'min': '375px',
'max': '667px'
},
'dp': {
'min': '414px',
'max': '736px'
},
'sm': {
'min': '640px',
'max': '767px'
},
'md': {
'min': '768px',
'max': '1023px'
},
'lg': {
'min': '1024px',
'max': '1279px'
},
'xl': {
'min': '1280px',
'max': '1535px'
},
'2xl': {
'min': '1536px'
},
},
extend: {},
},
variants: {
extend: {},
},
// add DaisyUI plugin
plugins: [
require('daisyui'),
],

// config (optional)
daisyui: {
styled: true,
themes: false,
base: false,
utils: true,
logs: true,
rtl: false,
},
}

// postcss.config.js
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}

 

Vite 默認為您生成的 ./src/index.css 文件

/* ./src/index.css */

/*! @import */
@tailwind base;
@tailwind components;
@tailwind utilities;

// src/main.js
import './index.css'

 

整合代碼規范插件eslint,prettier
安裝依賴

yarn add babel-eslint -D
yarn add @vue/eslint-config-prettier -D
yarn add eslint -D
yarn add eslint-plugin-prettier -D
yarn add eslint-plugin-vue -D
yarn add prettier -D
復制代碼

 

根目錄建 ​​.eslintrc.js​​

//.eslintrc.js
module.exports = {
root: true,
env: {
node: true,
},
extends: ['plugin:vue/vue3-essential', 'eslint:recommended'],
parserOptions: {
parser: 'babel-eslint',
},
rules: {
//在此處寫規則
'no-unused-vars': 0, // 定義未使用的變量
},
};
復制代碼

 

根目錄建 ​​.prettierrc.json​​

//.prettierrc.json
{
//此處填寫規則
"singleQuote": true,//單引號
"seme": true,//分號
"tabWidth": 2,//縮進
"TrailingCooma": "all",//尾部元素有逗號
"bracketSpacing": true,//對象中的空格
}
復制代碼

 

​​vscode​​ 自動格式化

//settings.json
"editor.formatOnSave": true,//保存時格式化
"files.autoSave": "onFocusChange", //失去焦點時保存
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"eslint.validate": [
"javascript",
"javascriptreact",
"typescript"
],

 

配置GZIP壓縮
安裝依賴

yarn add vite-plugin-compression -D

修改 ​​vite.config.js​​

//vite.config.js

import viteCompression from 'vite-plugin-compression'
plugins:[
...
viteCompression({
verbose: true,
disable: false,
threshold: 10240,
algorithm: 'gzip',
ext: '.gz'
})
]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM