What is the Vite

Vite itself has nothing to do with the framework, is a set of plugin-based project engineering architecture, is a new set of developer friendly a set of construction and development tools, its characteristics is fast, it will not let your development process become stuck with the scale of the project. To summarize: Vite is a development build tool, it uses the browser’s Native ES Module feature to import source code on demand, pre-packaged dependencies. Is a set of development tools tailored for developers. Features: quick start, quick update.

How Vite works

We looked at the structure of the Vite project and found an index. HTML file in the root directory. This file is somewhat equivalent to the HTML template entry file in our previous WebPack project. One of the biggest changes is that script tag references are made with ES6’s native modularity type=”module”, i.e., ESModule.

<script type="module" src="/src/main.ts"></script>
Copy the code

This means that you can use ES6 to write code in your project, and the browser will use HTTP to request your import files. The diagram below:

Vue. Js, app. vue and index.css were imported from main.js, and subsequent HTTP requests were made for relevant file contents.

Let’s look at what app. vue requests back:

It’s already been parsed.

The app. vue request response is content-Type: application/javascript

This means that the app. vue file is no longer the vue file we wrote, but a JS file that can be executed by the browser after being parsed by the Vite server.

The installation

npm init @vitejs/app
Copy the code

I chose the vuE-TS default configuration

The resource reference

Import resources as urls

Importing a static resource from a service returns the parsed public path:

import logo  from "./assets/logo.png"
Copy the code

use

<img alt="logo" :src="logo" />
Copy the code

We can see that the address of the parsed image becomes an absolute address

Reference image in CSS background

.logo {
    background-image: url(./assets/logo.png);
    width: 100px;
    height: 100px;
}
Copy the code

Set an alias

In the vite. Config file

export default defineConfig({
  resolve: {
    alias: {
        The '@': resolve('./src'),
        'comps': resolve('./src/components')}},plugins: [vue()]
})
Copy the code

Global style

This can be introduced in main.ts

import { createApp } from 'vue'
import App from './App.vue'
import './index.css'
createApp(App).mount('#app')
Copy the code

CSS modular

Write the CSS in module mode

<style module>
.logo {
    background-image: url(@/assets/logo.png);
    width: 200px;
    height: 200px;
}
</style>
Copy the code

This will give you a $style variable

<div :class="$style.logo"></div>
Copy the code

The nice thing about this is that the class name will be hashed to become a unique class name

It can also be written in the convention way

import styles from './App.module.css'
Copy the code
<div :class="styles.logo"></div>
Copy the code

Sass or less style processor

As the project gets bigger and we want to organize more style, we usually introduce style processors like Sass or Less

Just install Sass, no extra configuration is required, such as installing the Loader like WebPack

npm i -D sass
Copy the code
<style scoped lang="scss">
$link-color: red;
a {
    color: $link-color
}
</style>
Copy the code

Autoprefixer configuration

Install autoprefixer

npm i autoprefixer -D
Copy the code

Then add a postcss.config.js file to the root directory

module.exports = {
  plugins: [
    require('autoprefixer')]}Copy the code

Write a

::placeholder{
    color: $link-color
}
Copy the code

The prefix is automatically added

Ts configuration

Vite integrates TS natively and you don’t need to do much extra configuration to use it. You can configure limited TypeScript versions in package.json

"devDependencies": {
    "typescript": "^ 4.3.2." ",}Copy the code

Configuring the Proxy Server

Just do the following in the root vite. Config file

export default defineConfig({
  server: {
    proxy: {
      '/api': {
        target: 'http://www.baidu.com'.changeOrigin: true.rewrite: (path) = > path.replace(/^\/api/.' '),},},},},})Copy the code

The mock data

Install dependencies

NPM I mockjs -s // Runtime dependencies so -s NPM I vite-plugin-mock -dCopy the code

The following configuration is also required in the vite. Config file in the root directory

import {viteMockServe} from 'vite-plugin-mock'
export default defineConfig({
	plugins: [viteMockServe({})],
})
Copy the code

Create a new mock file in the root directory

Write an analog interface

export default[{url: "/api-dev/user/list".method: "get".response: req= > {
      return {
        code: 0.data: [{ id: 1.name: "coboy" }, { id: 2.name: "cobyte"}]}; }}];Copy the code

Write one more request

fetch("/api-dev/user/list").then(res= > res.json()).then(r= > console.log(r))
Copy the code

Write correctly and you can see the printed data on the console.

Code specification

Use the esLint + Prettier specification project code, where ESLint normalizes detection and prettier formats

Install dependencies

{
  "@typescript-eslint/eslint-plugin": "^ 4.15.2"."@typescript-eslint/parser": "^ 4.15.2"."@vue/eslint-config-prettier": "^ 6.0.0"."@vue/eslint-config-typescript": "^ 7.0.0." "."@vuedx/typescript-plugin-vue": "^ 0.6.3"."eslint": "^ 7.20.0"."eslint-plugin-prettier": "^ 3.3.1"."eslint-plugin-vue": "^ 7.6.0"."prettier": "^ 2.2.1." ",}Copy the code

Eslint verifies.vue files using the eslint-plugin-vue plugin

Configure the.eslintrc.js file

module.exports = {
  root: true.env: {
    browser: true.es2021: true.node: true
  },
  extends: [
    'plugin:vue/vue3-recommended'.'eslint:recommended'.'@vue/typescript/recommended'.'@vue/prettier'.'@vue/prettier/@typescript-eslint'].parserOptions: {
    ecmaVersion: 2021
  },
  plugins: [].rules: {
    'no-unused-vars': 'off'.'@typescript-eslint/no-unused-vars': 'off'}}Copy the code

Configure the package detection command

"lint": "eslint --ext .ts,tsx,vue src/** --no-error-on-unmatched-pattern --quiet",
"lint:fix": "eslint --ext .ts,tsx,vue src/** --no-error-on-unmatched-pattern --fix"
Copy the code

–quiet Displays no warning

–fix Automatic repair

Configure files that ignore check. Eslintignore

*.css
*.less
*.scss
*.jpg
*.png
*.gif
*.svg
*vue.d.ts
Copy the code

Test configuration

Test components using jest and @vue/test-utils

Install dependencies

"Jest" : "^ 26.6.3", "@ types/jest" : "^ 26.0.20", "vue - jest" : "^ 5.0.0 - alpha. 7", "Babel - jest" : "^ 26.6.3 @", "Babel/preset - env" : "^ 7.12.17", "@ vue/test - utils" : "^ 2.0.0 - beta. 9", "ts - jest" : "^ 26.5.1 @", "Babel/preset - the typescript" : "^ 7.12.17",Copy the code

Configure the jest. Config.js file

module.exports = {
  transform: {
    // Use 'vue-jest' to process '*. Vue' files
    '^.+\\.vue$': 'vue-jest'.'^.+\\.jsx? $': 'babel-jest'.// Adding this line solved the issue
    '^.+\\.tsx? $': 'ts-jest',},// support alias
  moduleNameMapper: {
    '^@/components(.*)$': '<rootDir>/src/components$1',},testMatch: ['**/tests/unit/**/*.[jt]s? (x)'],}Copy the code

Configure jest in the tsconfig.json file

"compilerOptions": {
	"types": ["vite/client"."jest"],}Copy the code

Configure the run command in package.json

"test:unit": "jest"
Copy the code

Ts may have some edgy syntax, so you need to configure Babel

Configure the Babel. Config. Js

module.exports = {
    presets: [["@babel/preset-env", { targets: { node: "current"}}]."@babel/preset-typescript",]};Copy the code

Run Lint at the same time as testing when committing

Install dependencies

"Lint - staged", "^ 10.5.4", "yorkie" : "^ 2.0.0." "Copy the code
"gitHooks": {
    "pre-commit": "lint-staged"."pre-push": "npm run test:unit"
},
"lint-staged": {
    "*.{js,vue}": "eslint --fix"
},
Copy the code

Configure a test file in the root directory

tests/unit/example.spec.ts

import HelloWorld from ".. /.. /src/components/HelloWorld.vue";
import { shallowMount } from "@vue/test-utils";

describe("test".() = > {
  test("should ".() = > {
    const wrapper = shallowMount(HelloWorld, {
      props: {
        msg: "hello,coboy",}}); expect(wrapper.text()).toMatch("hello,coboy");
  });
});
Copy the code

If the following command output is displayed, the configuration is successful

If the following information is displayed when git push is executed, the configuration is successful

Error Unexpected trailing comma.comma-dangle Error Eslint code detects report data

Vs Code’s File-Preferences – Settings, search for ‘comma’, add:

Prettier: Trailing Comma

Set it to “None”.

Making the address