Vue3+Vite+TypeScript common project module details

Time:2024-2-29

 

catalogs

1. Vue3+Vite+TypeScript Overview

1.1 vue3 

1.1.1 Vue3 Overview

1.1.2 Current status and development trend of vue3

1.2 Vite

1.2.1 Realities

1.2 Build the vite project

1.3 TypeScript

1.3.1 TypeScript Definitions

1.3.2 TypeScript Basic Data Types

1.3.3 A Brief Introduction to TypeScript Syntax

2. Brief overview of project configuration

2.1 eslint Checksum Tool Configuration

2.1.1 eslint definition

2.1.2 eslint installation

2.2 prettier formatting tool configuration

2.2.1 prettier

2.2.2 Installing prettier

2.3 stylelint Configuration

2.3.1 Definition of stylelint

2.3.2 scss installing stylelint dependencies

2.4 husky placement

2.4.1 Definition of husky

2.4.2 husky installation

3. Project Integration

3.1 Integration of element-plus

3.1.1 Installation

3.1.2 Applications

3.2 Configuration of src aliases

3.3 Mock

3.3.1 Mock Definitions

3.3.2 Mock Usage Scenarios

3.3.3 Installation and testing

3.4 axios encapsulation

3.5 Integrating Sass

3.5.1 Introduction to sass

3.5.2 Installation

3.5.3 sass syntax


 

Now regardless of gitee or github, more and more front-end open source projects using Vue3 + Vite + TypeScript + Pinia + Elementplus + axios + Sass (css precompiled language , etc.), which there are a variety of project configurations such as eslint Verification of the code tool configuration , etc., and we want to carry out front-end project secondary development, it is necessary to understand the use of these things, so the author wrote this article for a brief introduction.

1. Vue3+Vite+TypeScript Overview

1.1 vue3 

1.1.1 Vue3 Overview

Vue.jsis a front-end JavaScript framework that can be used to build interactive web pages and single-page applications.Vue.js 3 is the latest version of the Vue.js framework, which was officially released in September 2020.Vue.js 3 has the following changes and improvements over Vue.js 2
1. Better performance: Vue.js3 has been optimized for performance and by optimizing the responsive system, you can improve the performance of your application.
2. Better TypeScript support: Vue.js 3 has better TypeScript support and built-in TypeScript support.
3. Better Developer Experience: Vue.js 3 has a major upgrade to the template compiler, where all raw templates are now compiled into functions, which means faster compilation and a runtime that relies less on Vue.js itself.
4. Better Component API: Vue.js 3 introduces the Composition API, which helps developers write component code more easily and flexibly.
5. Better Tree-Shaking Support: Vue.js 3 supports better tree-shaking functionality. It allows you to include only the code you need in your application, which greatly reduces load time and application size.

1.1.2 Current status and development trend of vue3

Currently.Vue 3 It has become one of the very popular frameworks for front-end development. Many companies and developers are using Vue 3 to develop their projects. Here are some of the trends in Vue 3:

1.Better TypeScript support: Vue 3 introduces a number of new TypeScript type definitions that provide better type checking and auto-completion. This makes it easier for developers to write Vue apps using TypeScript.
2.Popularity of Composition API: The Composition API is a new component API introduced in Vue 3 that helps developers better organize and reuse component logic. As more and more developers start using the Composition API, it will become an important part of Vue 3 development.
3.Faster performance and smaller package size: Vue 3 introduces a number of performance optimizations, including faster rendering, smaller package size, and more. These improvements make Vue 3 a more efficient and reliable framework that helps developers build high-quality applications faster.
4.More Community Contributions: Vue 3 already has broad community support, with many developers and companies working on new plugins, components, and tools for Vue 3. This will further enhance the functionality and usability of Vue 3.

 

1.2 Vite

1.2.1 Realities

Until browsers supported ES modules, JavaScript didn’t provide a native mechanism for developers to work in a modular fashion. That’s why we’re familiar with the concept of “packaging”: using tools to grab, manipulate, and string together our source code modules into files that run in the browser.

Time has passed and we have witnessed such things aswebpackRollup respond in singingParcel and other tools have changed, and they have dramatically improved the development experience for front-end developers.

However, as we started to build larger and larger applications, the amount of JavaScript code that needed to be processed grew exponentially. Large projects with thousands of modules are quite common. JavaScript-based development tools then start to run into performance bottlenecks: it often takes a long time (even minutes!) It usually takes a long time (even minutes!) for the development server to start up, and even with Hot Module Replacement (HMR), it takes a few seconds for file changes to be reflected in the browser. This cycle of sluggish feedback can dramatically impact developer productivity and happiness.

Vite aims to address these issues by taking advantage of new developments in the ecosystem: browsers are starting to support ES modules natively, and more and more JavaScript tools are being written in compiled languages.

1.2 Build the vite project

Using NPM.

npm create vite@latest

Using PNPM.

pnpm create vite

1.3 TypeScript

1.3.1 TypeScript Definitions

TypeScript, abbreviated as TS, is a superset of JavaScript. TypeScript is a superset of JavaScript, adding type support to JS. TypeScript = Type + JavaScript

1.3.2 TypeScript Basic Data Types

As shown in the figure below:

Vue3+Vite+TypeScript common project module details

1.3.3 A Brief Introduction to TypeScript Syntax

1.3.3.1 Original type

// Numeric type
let age: number = 20
 
// String type
let myName: string = 'hello'
 
// Boolean type
let isLoading: boolean = false
 
// undefined
let un: undefined = undefined
 
// null
let timer:null = null

1.3.3.2 Types of association

let variable: type 1 | type 2 | type 3 .... = initial value

 

let arr: (number | string)[] = [12, 'a']

1.3.3.3 Array types

let variable: type [] = [value 1, ...]

let variable: Array<type> = [value 1, ...]

let numbers: number[] = [40, 43, 45] 

1.3.3.4 Function types


ordinary function (math.): function function name(formal1: type, formal2: type): return value type { }
arrow function: const function name (formal1: type, formal2: type): return value type => { }

// Function declarations
function add(num1: number, num2: number): number {
  return num1 + num2
}

// Arrow functions
const add = (num1: number, num2: number): number => {
  return num1 + num2
}

1.3.3.5 Interfaces

When an object type is used multiple times, there are two ways to describe the object type for reuse purposes.

interface interface name {
    Attribute 1: Type 1, Attribute 2: Type 2,
}
interface login_form {
    username:string,
    password:string
}

If two interfaces have the same properties or methods between them, the common properties or methods can be abstracted away and reused through inheritance

interface interface1 extends interface2 to enable reuse of attributes or methods.

1.3.3.6 Pantypes

Generic types, as the name suggests, are broad types, that is, types that are not fixed; they can be applied to more than one type, and the use of a type variable (e.g., T) helps us to capture the incoming type, after which we can continue to use that type.

generalized function

// T is just a name, it can be changed to something else, e.g. R
 
function fn<T>(value: T): T { return value }
const num = fn<number>(10)

generic interface
 

interface myinterface<T> {
        list:Array<T> 
}

Of course there is a lot more to ts, so here is just a brief introduction.

2. Brief overview of project configuration

2.1 eslint Checksum Tool Configuration

2.1.1 eslint definition

The official website tells us that ESLint is a code inspection tool used to identify ECMAScript/JavaScript and give reports according to the rules, oh, so we can know that ESLint is a tool, and it is a tool used to check the code.

Code checking is a static analysis, often used to find problematic patterns or code, and is not dependent on a specific coding style. Code checking is available for most programming languages, and generally compiled programs have built-in checking tools.

JavaScript is a dynamic and weakly typed language that is prone to errors in development. Because there is no compiler, finding errors in JavaScript code usually requires constant debugging during execution, and tools like ESLint allow programmers to find problems during coding, rather than during execution.

2.1.2 eslint installation

Install eslint

pnpm i eslint -D

Generate configuration file: .eslint.cjs

npx eslint --init

2.2 prettier formatting tool configuration

2.2.1 prettier

With eslint, why do we need prettier? eslint is for javascript, he is a detection tool, including js syntax and a small number of formatting issues, in eslint view, the syntax is right to ensure that the code works properly, formatting issues belong to the second;

Prettier belongs to the formatting tool , it is not accustomed to formatting is not uniform , so it did not do a good job on the eslint thing then do , in addition, prettier support for a variety of languages, including js. Summarize , eslint and prettier these two brothers a guarantee of js code quality , a guarantee of code beauty .

2.2.2 Installing prettier

pnpm install -D eslint-plugin-prettier prettier eslint-config-prettier

2.3 stylelint Configuration

2.3.1 Definition of stylelint

stylelintLint tool for css. Can format css code , check css syntax errors and unreasonable writing , specify the order of css writing and so on.

2.3.2 scss installing stylelint dependencies

The project uses scss as a preprocessor and installs the following dependencies:

pnpm add sass sass-loader stylelint postcss postcss-scss postcss-html stylelint-config-prettier stylelint-config-recess-order stylelint-config-recommended-scss stylelint-config-standard stylelint-config-standard-vue stylelint-scss stylelint-order stylelint-config-standard-scss -D

2.4 husky placement

2.4.1 Definition of husky

We’ve integrated our code validation tool above, but we need to manually execute the command each time to format our code. If someone commits to a remote repository without formatting, the specification is useless. So we need to force the developer to submit the code according to the specification.

To do this, we need to use husky to trigger a git hook before the code is committed, and then execute pnpm run format to format our code automatically.

2.4.2 husky installation

mountinghusky

pnpm install -D husky

fulfillment

npx husky-init

A .husky directory will be created in the root directory, and underneath this directory there will be a pre-commit file with commands that will be executed when we execute commit.

 

3. Project Integration

3.1 Integration of element-plus

element-plus is based on Vue 3, a component library for designers and developers.

3.1.1 Installation

Install element-plus

pnpm install element-plus

Installation of component libraries

pnpm install element-plus @element-plus/icons-vue

3.1.2 Applications

The entry file main.ts installs element-plus globally.

import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import elementplus from 'element-plus'
import 'element-plus/dist/index.css'
const app=createApp(App)
app.use(elementplus).mount('#app')

Component Usage

<script setup lang="ts">
 import {Plus} from '@element-plus/icons-vue'
</script>

<template>
  <div>
    <el-button type="primary" :icon="Plus">hello</el-button>
  </div>

</template>

3.2 Configuration of src aliases

File-to-file relationships can be complex when developing a project, so we need to configure an alias for the src folder.

// vite.config.ts
import {defineConfig} from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
export default defineConfig({
    plugins: [vue()],
    resolve: {
        alias: {
            "@": path.resolve(". /src") // Relative path alias configuration, using @ instead of src
        }
    }
})

TypeScript Compilation Configuration

// tsconfig.json
{
  "compilerOptions": {
    "baseUrl": ". /", // Parses the base address of a non-relative module, defaults to the current directory.
    "paths": { // path mapping, relative to baseUrl
      "@/*": ["src/*"] 
    }
  }
}

3.3 Mock

3.3.1 Mock Definitions

MockA test is a test method in which a virtual object is created in order to test certain objects that are not easily constructed or easily accessible.
MockYou can simulate the background response of an http interface, it’s as simple as that, you can simulate request, response.

3.3.2 Mock Usage Scenarios

1. Calling third-party systems without being able to build a demo environment for the customer.
2. Calling third-party systems without being able to conduct stable development tests
3. Calling third-party systems without being able to perform performance tests on your own system
4. The back-end has not completed the interface development, the front-end to be a step ahead of development
5. The return value of the real scenario does not cover the test scenario

3.3.3 Installation and testing

Installation of dependencies

pnpm install -D [email protected] mockjs

Enable the plugin in the vite.config.ts configuration file.

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


export default ({ command })=> {
  return {
    plugins: [
      vue(),
      viteMockServe({
        localEnabled: command === 'serve',
      }),
    ],
  }
}

Create a mock folder in the root directory: to create the mock data and interface we need, create a user.ts file inside the mock folder

// User information data
function createUserList() {
    return [
        {
            username: 'admin',
            password: '111111',
        },
        {
            username: 'system',
            password: '111111',
        },
    ]
}

export default [
    // User login interface
    {
        url: '/user/login',//request address
        method: 'post',//request method
        response: ({ body }) => {
            // Get the username and password carried in the request body.
            const { username, password } = body;
            //Calls the user information function to determine if there is a user.
            const checkUser = createUserList().find(
                (item) => item.username == username && item.password == password,
            )
            //No user returns a failure message
            if (!checkUser) {
                return { code: 201, data: { message: 'Account or password incorrect' } }
            }
            // Return success message if available
            const { token } = checkUser
            return {code: 200, data: {message: 'Login successful '}}
        },
    },

]

Finally it can be tested via axios.

3.4 axios encapsulation

In the development of the project can not be avoided with the back-end interaction , so we need to use axios plugin to send network requests. In the development of the project we will often be axios for the second package.

1: Using a request interceptor.Some operations can be handled in the request interceptor (start progress bar, request header carrying public parameters)

2: Using response interceptors.Some operations can be handled in the response interceptor (end of progress bar, simplifying the data returned from the server, handling http network errors)

import axios from "axios";
import { ElMessage } from "element-plus";
// Create an instance of axios
let request = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API,
    timeout: 5000
})
// Request interceptor
request.interceptors.request.use(config => {
    return config;
});
//Response Interceptor
request.interceptors.response.use((response) => {
    return response.data;
}, (error) => {
    // Handling network errors
    let msg = '';
    let status = error.response.status;
    switch (status) {
        case 401:
            msg = "Token expired";
            break;
        case 403:
            msg = 'No access authorization';
            break;
        case 404:
            msg = "Error requesting address";
            break;
        case 500:
            msg = "There was a problem with the server";
            break;
        default:
            msg = "No network";

    }
    ElMessage({
        type: 'error',
        message: msg
    })
    return Promise.reject(error);
});
export default request;

3.5 Integrating Sass

3.5.1 Introduction to sass

Sass is a precompiled language for CSS. It providesVariablesNested rules、 Mixing (mixins)、 FunctionsSass helps to keep complex stylesheets more organized and makes it easy to share designs within and across projects.

3.5.2 Installation

pnpm install sass sass-loader

But you’ll notice that there’s no way to use variables in the src/styles/index.scss global styles file , so you’ll need to introduce global variables to the project. Create a variable.scss file in style/variable.scss! This is where the global variables are stored and then configured in vite.config.ts as follows:
 

export default defineConfig((config) => {
	css: {
      preprocessorOptions: {
        scss: {
          javascriptEnabled: true,
          additionalData: '@import "./src/styles/variable.scss";',
        },
      },
    },
	}
}

Once configured you’ll see that scss provides these global variables to be used in component styles.

3.5.3 sass syntax

variant

In sass we can define repeatedly used css attributes as variables, and then refer to them by their names, so that we don’t have to write the value of the attribute over and over again, using the $ symbol to define the variable. In sass variable names, underscores and underscores are equivalent and are not distinguished.

$highlight-border: 1px solid red;

normal nesting

sass provides a nested way to write only once and with higher readability

 div{
        h1{
            color:$red;
        }
    }

pseudo-class selector

When we use the pseudo-class selector for the

article a {
    color: blue;
    :hover { color: red }
}

The compiled css code looks like this

article a {
  color: blue;
}
article a :hover {
  color: red;
}

This time sass provides & for us to use, & represents the selector of our parent class, here the & represents article a, we can write the sass code like this

article a {
    color: blue;
    &:hover { color: red }
}

Mixer mixin

We can define a large css style with the @mixin identifier and then reuse it in different places with @include

@mixin alert {
    background-color: yellow;
    color: red;
}
    h1{
        @include alert
    }

Mixers support parameter passing like functions to achieve module customization

@mixin alert($text-color,$backgroud-color) {
    background-color: $backgroud-color;
    color: $text-color;
}
    h1{
        @include alert(red,blue)
    }

predecessor

Inheritance is a very important feature in SASS that allows you to reuse CSS properties between selectors with the @extend directive and without creating redundant code.

@mixin alert($text-color,$backgroud-color) {
    background-color: $backgroud-color;
    color: $text-color;
}
    h1{
        @include alert(red,blue)
    }
    h2{
        @extend h1
    }

@import

 sass can import other sass files via @import to achieve a modular effect, those special files for other sass files to import are called partial files, sass has a special convention for naming these files. Sass has a special convention for naming these files, which is to start them with an underscore, which can be omitted when importing. For example, if you want to importstyles/_a.scssvariables in this localized file, you can simply write the style sheet@import "styles/a"。

This article comes to an end, due to the length of many of the contents of which is only a simple introduction to the more commonly used content, the latter will be split into the content of each module for a detailed introduction and code combat.

Vue3+Vite+TypeScript common project module details

 

 

 

 

Recommended Today

The 100 Best Deep Learning Projects for Getting Started

attention (heed): Recently by the fans feedback, found that some subscribers will be the content of this column for secondary sale, hereby declare that the content of this column is for learning only, shall not be sold in any way, without the author’s permission shall not be the content of this column to exercise the […]