1. 程式人生 > 其它 >vite + vue3 + ts搭建專案

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

  1. npm i vuex@next
  2. 建立 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

  1. npm i axios
  2. 配置 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'
  })
]