Hello, I’m XY 👨🏻💻. It’s been a year since I first touched the vue3 version. With the release of vue3.2, the

Preparation before construction

  1. Vscode: front-end people must write code magic device
  2. Chrome: developer-friendly browser (I rely on it anyway)
  3. Nodejs&npm: Configure the local development environment. After installing Node, you will find that NPM is installed as well
  4. Vue.js devtools: browser debugging plug-in
  5. Vue Language Features (Volar): Vscode development vue3 necessary plug-in, provide syntax highlighting tips, very easy to use
  6. Vue 3 Snippets: Vue3 quick input

Since VueDevTools needs to be downloaded from the Google Extension store, xy at intimate ❤️ has prepared the CRX file for you. The official account reply: [VueDevTools] can be automatically obtained at 💪

Differences between Vue2 and Vue3

Because Vue3 is completely rewritten by TS, the definition and use of type judgment in the application has a strong performance. Multiple key return values of the same object must be typed by defining corresponding interfaces. Otherwise an error will be reported on ESLint.

The two-way data binding of VUe2 is implemented using an ES5 API called Object.definepropert () to hijack the data in conjunction with the published-subscribe model. Vue3 uses ES6 ProxyAPI for data proxy.

Vue3 supports Fragments

The biggest difference between Vue2 and Vue3 is that Vue2 uses the Options API while Vue3 uses the Composition API

Lifecycle hook changes:

Vue2 ~~~~~~~~~~~ vue3
beforeCreate  -> setup()
created       -> setup()
beforeMount   -> onBeforeMount
mounted       -> onMounted
beforeUpdate  -> onBeforeUpdate
updated       -> onUpdated
beforeDestroy -> onBeforeUnmount
destroyed     -> onUnmounted
activated     -> onActivated
deactivated   -> onDeactivated
Copy the code

Introduce vite

Vite: Next-generation front-end development and build tools

  • 💡 extremely fast development server startup
  • ⚡️ Lightweight and fast Hot module overload (HMR)
  • 🛠️ Rich features
  • 📦 comes with an optimized build
  • 🔩 Common plug-in interface
  • 🔑 fully typed API

Vite (French for quick, pronounced /vit/) is a new front-end build tool that dramatically improves the front-end development experience.

It mainly consists of two parts:

  • A development server that provides rich built-in features based on native ES modules, such as surprisingly fast module hot update (HMR).

  • A set of build instructions that use Rollup to package your code and that are pre-configured to output optimized static resources for production.

  • Vite is intended to provide out-of-the-box configuration, while its plug-in API and JavaScript API provide a high degree of extensibility and complete type support.

Use Vite to quickly create scaffolding

Compatibility note :Vite requires node.js version >= 12.0.0.

  1. Step 1: Open it in the directory where you want to create the project filecmdRun the following command
# npm 6.x
npm init @vitejs/app vite_vue3_ts --template

# NPM 7+ requires additional double lines:
npm init @vitejs/app vite_vue3_ts -- --template

# yarn
yarn create @vitejs/app vite_vue3_ts --template
Copy the code

Here I use YARN to install

  1. Step 2: ChoosevueEnter = >vue-tsenter

  1. Step 3:cdGo to the project folder, install dependencies, and start the project
Enter the project folder
cd vite_vue3_ts
# install dependencies
yarn
# start
yarn dev
Copy the code

Constrained code style

Eslint support

# eslint installation
yarn add eslint --dev
Install the # esLint plugin
yarn add eslint-plugin-vue --dev

yarn add @typescript-eslint/eslint-plugin --dev

yarn add eslint-plugin-prettier --dev

# typescript parser
yarn add @typescript-eslint/parser --dev
Copy the code

Note: If ESLint installs an error:

Try running the following command:

yarn config set ignore-engines true
Copy the code

Run the esLint install command again after success

Create.eslintrc.js under the project

Configure esLint validation rules:

module.exports = {
  root: true.env: {
    browser: true.node: true.es2021: true,},parser: 'vue-eslint-parser'.extends: [
    'eslint:recommended'.'plugin:vue/vue3-recommended'.'plugin:@typescript-eslint/recommended'.'plugin:prettier/recommended'.// eslint-config-prettier
    'prettier',].parserOptions: {
    ecmaVersion: 12.parser: '@typescript-eslint/parser'.sourceType: 'module'.ecmaFeatures: {
      jsx: true,}},// eslint-plugin-vue @typescript-eslint/eslint-plugin Short for eslint-plugin-prettier
  plugins: ['vue'.'@typescript-eslint'.'prettier'].rules: {
    '@typescript-eslint/ban-ts-ignore': 'off'.'@typescript-eslint/no-unused-vars': 'off'.'@typescript-eslint/explicit-function-return-type': 'off'.'@typescript-eslint/no-explicit-any': 'off'.'@typescript-eslint/no-var-requires': 'off'.'@typescript-eslint/no-empty-function': 'off'.'@typescript-eslint/no-use-before-define': 'off'.'@typescript-eslint/ban-ts-comment': 'off'.'@typescript-eslint/ban-types': 'off'.'@typescript-eslint/no-non-null-assertion': 'off'.'@typescript-eslint/explicit-module-boundary-types': 'off'.'no-var': 'error'.'prettier/prettier': 'error'.// Disable console
    'no-console': 'warn'./ / disable the debugger
    'no-debugger': 'warn'.// Disallow duplicate case tags
    'no-duplicate-case': 'warn'.// Disallow empty statement blocks
    'no-empty': 'warn'.// Disallow unnecessary parentheses
    'no-extra-parens': 'off'.// Disallow reassignment of function declarations
    'no-func-assign': 'warn'.// Disallows unreachable code after return, throw, continue, and break statements
    'no-unreachable': 'warn'.// Force all control statements to use the same parenthesis style
    curly: 'warn'.// Require a default branch in the switch statement
    'default-case': 'warn'.// Force the use of dots whenever possible
    'dot-notation': 'warn'.// Use === and! = =
    eqeqeq: 'warn'.Disallow an else block after a return statement in an if statement
    'no-else-return': 'warn'.// Disallow null functions
    'no-empty-function': 'warn'.// Disable unnecessary nesting blocks
    'no-lone-blocks': 'warn'.// Disallow multiple Spaces
    'no-multi-spaces': 'warn'.// Do not declare the same variable more than once
    'no-redeclare': 'warn'.// Disallow assignment statements in return statements
    'no-return-assign': 'warn'.// Disable unnecessary return await
    'no-return-await': 'warn'.// Disallow self-assignment
    'no-self-assign': 'warn'.// Disallow self comparison
    'no-self-compare': 'warn'.// Disallow unnecessary catch clauses
    'no-useless-catch': 'warn'.// Disallow redundant return statements
    'no-useless-return': 'warn'.// Disallow variable declarations with the same name as variables in the outer scope
    'no-shadow': 'off'.// Allow delete variables
    'no-delete-var': 'off'.// Enforces consistent Spaces in array square brackets
    'array-bracket-spacing': 'warn'.// Enforce a consistent brace style in code blocks
    'brace-style': 'warn'.// Enforce camel spelling naming conventions
    camelcase: 'warn'.// Enforce consistent indentation
    indent: 'off'.// Enforce consistent use of double or single quotes in JSX attributes
    // 'jsx-quotes': 'warn',
    // Enforces a maximum depth of 4 for blocks that can be nested
    'max-depth': 'warn'.// Enforces a maximum of 300 rows
    // "max-lines": ["warn", { "max": 1200 }],
    // Enforces a maximum of 50 lines of code for the function
    // 'max-lines-per-function': ['warn', { max: 70 }],
    // Enforces the maximum number of statements allowed in a function block to be 20
    'max-statements': ['warn'.100].// Enforces maximum nesting depth for callback functions
    'max-nested-callbacks': ['warn'.3].// Enforces the maximum number of arguments allowed in a function definition
    'max-params': ['warn'.3].// Enforces the maximum number of statements allowed in each line
    'max-statements-per-line': ['warn', { max: 1}].// Require a newline character for each call in the method chain
    'newline-per-chained-call': ['warn', { ignoreChainWithDepth: 3}].// Disallow if as the only statement in else statements
    'no-lonely-if': 'warn'.// Disallow the combination of space and TAB indentation
    'no-mixed-spaces-and-tabs': 'warn'.// Disallow multiple blank lines
    'no-multiple-empty-lines': 'warn'.// Prohibit the occurrence of;
    semi: ['warn'.'never'].// Enforces consistent whitespace before blocks
    'space-before-blocks': 'warn'.// Enforces a consistent space before the opening parenthesis of function
    // 'space-before-function-paren': ['warn', 'never'],
    // Enforces consistent Spaces inside parentheses
    'space-in-parens': 'warn'.// Requires Spaces around the operator
    'space-infix-ops': 'warn'.// Enforces consistent Spaces around unary operators
    'space-unary-ops': 'warn'.// Enforces consistent whitespace in comments
    // "spaced-comment": "warn",
    // Enforces a space around the colon of switch
    'switch-colon-spacing': 'warn'.// Forces the arrow function to use consistent Spaces before and after the arrow
    'arrow-spacing': 'warn'.'no-var': 'warn'.'prefer-const': 'warn'.'prefer-rest-params': 'warn'.'no-useless-escape': 'warn'.'no-irregular-whitespace': 'warn'.'no-prototype-builtins': 'warn'.'no-fallthrough': 'warn'.'no-extra-boolean-cast': 'warn'.'no-case-declarations': 'warn'.'no-async-promise-executor': 'warn',},globals: {
    defineProps: 'readonly'.defineEmits: 'readonly'.defineExpose: 'readonly'.withDefaults: 'readonly',}}Copy the code

Create.eslintignore under the project

# esLint ignores checks (add your own for your project)
node_modules
dist
Copy the code

Prettier support

# installation prettier
yarn add prettier --dev
Copy the code

Resolve a conflict between ESLint and Prettier

Prettier solves the conflict between the style specification in ESLint and the style specification in Prettier by taking the style specification in Prettier as the criterion

# Install the plugin eslint-config-prettier
yarn add eslint-config-prettier --dev
Copy the code

Create.prettier.js under the project

Configuring the formatting rule for the prettier node:

module.exports = {
  tabWidth: 2.jsxSingleQuote: true.jsxBracketSameLine: true.printWidth: 100.singleQuote: true.semi: false.overrides: [{files: '*.json'.options: {
        printWidth: 200,}},],arrowParens: 'always',}Copy the code

Create.prettierIgnore under the project

# Ignore formatting files (add your own according to project needs)
node_modules
dist
Copy the code

Package. Json configuration:

{
  "script": {
    "lint": "eslint src --fix --ext .ts,.tsx,.vue,.js,.jsx"."prettier": "prettier --write ."}}Copy the code

After the above configuration is complete, you can run the following command to test the following code to check the formatting effect:

# eslint check
yarn lint
# prettier automatically formatting
yarn prettier
Copy the code

Configure HusKY + Lint-staged

Husky + Lint-staged installations are recommended for HUSky & Lint-staged installations using MRM, which will install and configure HusKY and Lint-staged installations according to code quality tools in package.json dependencies. So be sure to install and configure all code quality tools, such as Prettier and ESlint, before you do this

Install MRM first

npm i mrm -D --registry=https://registry.npm.taobao.org
Copy the code

Husky is a tool that adds hooks to Git clients. Once installed, it automatically adds hooks to the.git/ directory in your repository. For example, a pre-commit hook will trigger when you perform a Git commit.

You can implement things like Lint checking, unit testing, and code beautification in pre-commit. Of course, make sure that the commands executed in the pre-commit phase are not too slow, and waiting too long for each commit is not a good experience.

Lint-staged, a tool that simply filters out Git code staging files (files added by Git); This is useful because if we do a review of the entire project code, it can take a long time, but if we do an older project, we have to do a code specification review and modify the previous code, which can be troublesome and lead to big changes in the project.

So this Lint-staged project is a great tool for team projects and open source projects, which act as a specification and discipline for the code that individuals must commit

Install the lint – staged

MRM installations Lint-staged will automatically mount Husky together

npx mrm lint-staged
Copy the code

After successful installation, you will find the following configurations in package.json:

Because we’re formatting with the prettier code, modify the configuration:

"husky": {
    "hooks": {
      "pre-commit": "lint-staged"}},"lint-staged": {
    "*.{js,jsx,vue,ts,tsx}": [
      "yarn lint"."prettier --write"."git add"]}Copy the code

Ok, here the code formatting configuration is basically done!!

You can modify part of the code and try git Commit. You will find that the code will be automatically formatted:

Code before submission (found the editor is exploding):

When the commit operation is performed, the console can see the flow:

Is the code already formatted after the commit

The configuration file references the alias

Modify the vite.config.ts file configuration directly:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      The '@': path.resolve(__dirname, 'src'),}}})Copy the code

Modify the tsconfig. Json

{
  "compilerOptions": {
    "target": "esnext"."module": "esnext"."moduleResolution": "node"."strict": true."jsx": "preserve"."sourceMap": true."resolveJsonModule": true."esModuleInterop": true."lib": ["esnext"."dom"]."baseUrl": "."."paths": {
      "@ / *": ["src/*"]}},"include": ["src/**/*.ts"."src/**/*.d.ts"."src/**/*.tsx"."src/**/*.vue"]}Copy the code

Configure the CSS preprocessor SCSS

Although Vite natively supports less/ Sass/SCSS/Stylus, you must manually install their preprocessor dependencies

The installation

yarn ass sass-loader --dev
yarn add dart-sass --dev
yarn add sass --dev
Copy the code

Configure the global SCSS style file

Add the style folder under SRC /assets to store global style files

Create a new main. SCSS and set a color variable for the test:

$test-color: red;
Copy the code

How do YOU inject this global style file globally into your project? Configure Vite:

css:{
    preprocessorOptions: {scss: {additionalData:'@import "@/assets/style/mian.scss"; '}}},Copy the code

Use in components

There is no need to introduce variables that can be defined directly using global SCSS

.test{
  color: $test-color;
}
Copy the code

routing

# Install route
yarn add vue-router@4
Copy the code

Add the router folder => router.ts file to the SRC file. The contents are as follows:

import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'

const routes: RouteRecordRaw[] = [
  {
    path: '/'.name: 'Login'.component: () = > import('@/pages/login/Login.vue'), // Note that the file suffix is.vue},]const router = createRouter({
  history: createWebHistory(),
  routes,
})

export default router

Copy the code

Modify import file mian. Ts:

import { createApp } from 'vue'
import App from './App.vue'
import router from './router/index'

const app = createApp(App)

app.use(router)

app.mount('#app')

Copy the code

The basic configuration of the route to this router has been completed. You can see the official documentation of vue-Router for more configuration information.

vue-router: https://next.router.vuejs.org/zh/guide/

Vue-router4. x supports typescript and configures the route type as RouteRecordRaw.

  • title:string; Page title, usually mandatory.
  • icon?:string; Icon, usually used with the menu.
  • auth?:boolean; Whether login permission is required.
  • ignoreAuth?:boolean; Whether to ignore permissions.
  • roles?:RoleEnum[]; Accessible role
  • keepAlive?:boolean; Whether to enable page caching
  • hideMenu?:boolean; There are some routes that we don’t want to show in menus, such as some edit pages.
  • order?:number; Menu sorting.
  • frameUrl?:string; Nested outer chain.

This section only provides some ideas. The services involved in each project will have some differences, so you can configure them based on your own service requirements.

Unified request encapsulation

Those of you who have used Vue2. X should be familiar with Axios. Here we use Axios directly for encapsulation:

# installation axios
yarn add axios
# Install nprogress for request loading
# You can also customize other loading according to project requirements
yarn add nprogress
Declare module 'nProgress'
yarn add @types/nprogress --dev
Copy the code

In practice, it can be modified according to the project. For example, RESTful apis can add PUT and DELETE requests, and ResType can be modified dynamically based on the general return value of the backend

New http.ts file and API folder under service:

Http. ts: Used for AXIOS encapsulation

//http.ts
import axios, { AxiosRequestConfig } from 'axios'
import NProgress from 'nprogress'

// Set the request header and request path
axios.defaults.baseURL = '/api'
axios.defaults.timeout = 10000
axios.defaults.headers.post['Content-Type'] = 'application/json; charset=UTF-8'
axios.interceptors.request.use(
  (config): AxiosRequestConfig<any> => {
    const token = window.sessionStorage.getItem('token')
    if (token) {
      //@ts-ignore
      config.headers.token = token
    }
    return config
  },
  (error) = > {
    return error
  }
)
// Response interception
axios.interceptors.response.use((res) = > {
  if (res.data.code === 111) {
    sessionStorage.setItem('token'.' ')
    // Token expired operation
  }
  return res
})

interface ResType<T> {
  code: number data? : Tmsg: string err? : string } interface Http { get<T>(url: string, params? : unknown):Promise<ResType<T>> post<T>(url: string, params? : unknown):Promise<ResType<T>>
  upload<T>(url: string, params: unknown): Promise<ResType<T>>
  download(url: string): void
}

const http: Http = {
  get(url, params) {
    return new Promise((resolve, reject) = > {
      NProgress.start()
      axios
        .get(url, { params })
        .then((res) = > {
          NProgress.done()
          resolve(res.data)
        })
        .catch((err) = > {
          NProgress.done()
          reject(err.data)
        })
    })
  },
  post(url, params) {
    return new Promise((resolve, reject) = > {
      NProgress.start()
      axios
        .post(url, JSON.stringify(params))
        .then((res) = > {
          NProgress.done()
          resolve(res.data)
        })
        .catch((err) = > {
          NProgress.done()
          reject(err.data)
        })
    })
  },
  upload(url, file) {
    return new Promise((resolve, reject) = > {
      NProgress.start()
      axios
        .post(url, file, {
          headers: { 'Content-Type': 'multipart/form-data' },
        })
        .then((res) = > {
          NProgress.done()
          resolve(res.data)
        })
        .catch((err) = > {
          NProgress.done()
          reject(err.data)
        })
    })
  },
  download(url) {
    const iframe = document.createElement('iframe')
    iframe.style.display = 'none'
    iframe.src = url
    iframe.onload = function () {
      document.body.removeChild(iframe)
    }
    document.body.appendChild(iframe)
  },
}
export default http

Copy the code

API: The interfaces in the project are managed uniformly and divided into modules

The login folder is added under the API file to store the request interface of the login module. The login.ts types.ts folder is added respectively.

login.ts:

import http from '@/service/http'
import * as T from './types'

const loginApi: T.ILoginApi = {
    login(params){
        return http.post('/login', params)
    }

}
export default loginApi
Copy the code

types.ts:

export interface ILoginParams {
    userName: string
    passWord: string | number
}
export interface ILoginApi {
    login: (params: ILoginParams) = > Promise<any>}Copy the code

At this point, a simple request wrapper completes!!!!

In addition to wrapping AXIos manually, there is a vue3 request library called VueRequest, which is very useful. Here are some useful features of VueRequest.

  • 🚀 All data is reactive
  • 🔄 polling request
  • 🤖 Automatic error handling retry
  • 🗄 Built-in request caching
  • 💧 Throttling request and anti-shake request
  • 🎯 automatically rerequests the focus page
  • ⚙️ powerful paging extensions and loading more extensions
  • 📠 is written entirely in Typescript with powerful type hints
  • ⚡ ️ compatible Vite
  • 🍃 lightweight
  • 📦 out of the box

Is not very powerful 💪

The official website link: www.attojs.com/

State management Pinia

Vuex 4’s support for typescript was disappointing, so state management abandoned Vuex in favor of Pinia. Pinia was written by a member of the Vue core team

Uvu seems to say that Pinia may replace vuex, so please feel free to use it.

Install pinia

Differences between Pinia and Vuex:

  • idIs required to connect the store used to DevTools.
  • Creation method:new Vuex.Store(...)(vuex3),createStore(...)(vuex4).
  • Compared to Vex3, state is now oneFunction return object.
  • There is nomutations, don’t worry, state changes are still recorded in DevTools.
# installation
yarn add pinia@next
Copy the code

In the main. Ts increases

# introductionimport { createPinia } from "pinia"# create the root repository and pass it to the app app.use(createPinia())Copy the code

Add the store folder in SRC folder, and then add main.ts in store

createstore, mian.ts :

import { defineStore } from 'pinia'

export const useMainStore = defineStore({
  id: 'mian'.state: () = >({
    name: 'Super Administrator'})})Copy the code

Get store in build:

<template>
  <div>{{mainStore.name}}</div>
</template>

<script setup lang="ts">
import { useMainStore } from "@/store/mian"

const mainStore = useMainStore()

</script>
Copy the code

Introduction to getters usage

Getters in Pinia have the same functionality as getters in Vuex and computed properties in components

store => mian.ts

import { defineStore } from 'pinia'

export const useMainStore = defineStore({
  id: 'mian'.state: () = > ({
    name: 'Super Administrator',}).// getters
  getters: {
    nameLength: (state) = > state.name.length,
  }
})
Copy the code

Components used in:

<template>
  <div>User name :{{mainstore.name}}<br />Length :{{mainStore.namelength}}</div>
  <hr/>
  <button @click="updateName">Example Change the name in store</button>
</template>

<script setup lang="ts">
import { useMainStore } from '@/store/mian'

const mainStore = useMainStore()

const updateName = () = >{
  $patch Modifies the data in the store
  mainStore.$patch({
    name: 'Name changed,nameLength changed with it'})}</script>
Copy the code

actions

Unlike Vuex, Pinia only provides a way to define how to change the rules of the state, abandoning mutations and relying solely on Actions, which is a major change.

Pinia makes Actions more flexible:

  • Can be through components or otheractioncall
  • From other sourcesstoreactionIn the call
  • Directly in thestoreCall on instance
  • supportsynchronousorasynchronous
  • There are any number of parameters
  • Can include logic on how to change the state (which is what Vuex’s mutations do)
  • can$patchMethod directly changes the status properties
import { defineStore } from 'pinia'

export const useMainStore = defineStore({
  id: 'mian'.state: () = > ({
    name: 'Super Administrator',}).getters: {
    nameLength: (state) = > state.name.length,
  },
  actions: {
    async insertPost(data:string){
      // Can do asynchronous
      // await doAjaxRequest(data);
      this.name = data; }}})Copy the code

Environment Variable Configuration

Vite provides two modes: Development with a development server and Production

New project root directory :.env.development:

NODE_ENV=development

VITE_APP_WEB_URL= 'YOUR WEB URL'
Copy the code

New project root directory :.env. Production:

NODE_ENV=production

VITE_APP_WEB_URL= 'YOUR WEB URL'
Copy the code

Components used in:

console.log(import.meta.env.VITE_APP_WEB_URL)
Copy the code

Configuration package. Json:

Packaging distinguishes between development and production environments

"build:dev": "vue-tsc --noEmit && vite build --mode development"."build:pro": "vue-tsc --noEmit && vite build --mode production".Copy the code

Use the component library Naive UI

Component library selection, here we choose Naive UI but why did we choose it? Can I just say what You recommend?

  • Official introduction:
    • aVue 3Component library
    • More complete,The theme is adjustable, the use ofTypeScriptNot too slow
    • A little meaning

The introduction still compares modest, since especially big recommend, affirmation has its advantage!!

Install the Naive UI

Install the component library
yarn add naive-ui
# install font
yarn add vfonts
Copy the code

How to use

import { NButton } from "naive-ui"
<n-button>naive-ui</n-button>
Copy the code

Configure the Config Provider globally

The global configuration sets the theme, language of the internal component, and the class name of the DOM from which the component is unloaded elsewhere.

<n-config-provider :locale="zhCN" :theme="theme">
    <! -- -- -- > container
</n-config-provider>
Copy the code

Especially with the theme configuration feature, I really like ❤️

There is no compulsion in the selection of component library, just choose the appropriate component library according to your own project needs

Vite common basic configurations

Basic configuration

Run the agent and package the configuration

server: {
    host: '0.0.0.0'.port: 3000.open: true.https: false.proxy: {}},Copy the code

Remove the console debugger from the production environment

build:{
  ...
  terserOptions: {
      compress: {
        drop_console: true.drop_debugger: true}}}Copy the code

Gz files are generated in the production environment

Enabling gzip can greatly compress static resources, which has a significant effect on the speed of page loading.

The use of Vite-plugin-compression allows you to compress resources in gzip or brotli mode. This step requires the cooperation of the server side. Vite can only help you package.gz files. This plugin is easy to use, you don’t even need to configure parameters, just import.

# installation
yarn add --dev vite-plugin-compression
Copy the code

Add to plugins:

import viteCompression from 'vite-plugin-compression'

// Gzip compressed the production environment to generate.gz files
viteCompression({
      verbose: true.disable: false.threshold: 10240.algorithm: 'gzip'.ext: '.gz',}).Copy the code

Eventually vite. Config. Ts

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
//@ts-ignore
import viteCompression from 'vite-plugin-compression'

// https://vitejs.dev/config/
export default defineConfig({
  base: '/'.// Package the path
  plugins: [
    vue(),
    // Gzip compressed the production environment to generate.gz files
    viteCompression({
      verbose: true.disable: false.threshold: 10240.algorithm: 'gzip'.ext: '.gz',})],// Configure the alias
  resolve: {
    alias: {
      The '@': path.resolve(__dirname, 'src'),}},css: {preprocessorOptions: {scss: {additionalData:'@import "@/assets/style/mian.scss"; '}}},// Start service configuration
  server: {
    host: '0.0.0.0'.port: 8000.open: true.https: false.proxy: {}},// Production environment package configuration
  // Remove the console debugger
  build: {
    terserOptions: {
      compress: {
        drop_console: true.drop_debugger: true,},},},})Copy the code

Common plug-in

You can check out the official documentation: vitejs.cn/plugins/

  • @vitejs/plugin-vueprovideVue 3Single-file component support
  • @vitejs/plugin-vue-jsxProvide the Vue 3JSXSupport (through the dedicated Babel conversion plug-in)
  • @vitejs/plugin-legacyProvide a traditional browser for packaged filescompatibilitysupport
  • unplugin-vue-componentsAutomatic import of components on demand
  • vite-plugin-compressionUse gzip or Brotli to compress resources
  • .

The hooks library is highly recommended

Because vue3. X is really like React hooks, it’s called hooks

VueUse:vueuse.org/

When I first saw this library, I immediately thought of ahooks from React

VueUse is a collection of utility functions based on the Composition API. In plain English, this is a package of utility functions that can help you quickly implement common functions without having to write them yourself. And encapsulation based on Composition API. Make you more comfortable in vue3.

💡 want to get vuE3 partners, hurry up to learn!!

💡 finally give you the warehouse address: github.com/xushanpei/v…

Write in the last

If you like my articles, please add me to wX: xSP_web_share as a friend and let’s talk about front-end technology.