I. Introduction to Vite

Vite (French for “fast”, pronounced /vit/) is a lighter, faster front-end build tool for modern browsers that significantly improves the front-end development experience. In addition to Vite, the well-known build tools for the front end are Webpack and Gulp. At present, Vite has released Vite2, Vite’s new plug-in architecture, silky development experience, and can be perfectly combined with Vue3.

Composition of 1.1 Vite

The Vite build tool consists of two parts:

  • A development server that provides rich built-in functionality such as module hot update (HMR) based on native ES modules.
  • A set of build instructions that use Rollup to package your code and that are pre-configured to output optimized static resources for production.

In general, Vite is expected to provide out-of-the-box configuration, while its plug-in API and JavaScript API provide a high degree of extensibility. However, compared to vuE-CLI configuration, Vite built projects still have a lot of configuration that developers need to handle themselves.

1.2 Browser Support

  • Development environment: Vite needs to be used in browsers that support dynamic import of native ES modules.
  • In production: Default supported browsers need to support the introduction of native ES modules via script tags. Older browsers can be supported via the official plugin @vitejs/ plugin-Legacy.

Second, environment building

2.1 Creating a Project

According to the Vite website, you can use NPM or YARN to initialize the Vite project, and the node.js version must be >= 12.0.0. Use NPM mode

NPM init vite@latest Project nameCopy the code

Using Yarn Mode

Yarn Create Vite Project nameCopy the code

In addition, you can specify project names and templates directly through additional command-line options. For example, to build a Vite + Vue project, run the following command:

# NPM 6. X NPM init @vitejs/app my-vue-app --template vue # NPM 7+  npm init @vitejs/app my-vue-app -- --template vue # yarn yarn create @vitejs/app my-vue-app --template vueCopy the code

After entering the command, follow the instructions. If your project needs to support TypeScript, you can select VUe-TS when initializing the project. Once the project is created, you can see that the project created by Vite is actually similar to the project directory structure created using vue-CLI.

2.2 integrated Vue – the Router

2.2.1 Installing and configuring vue-Router

Vue-router, as an essential routing tool for most projects, has been used by most front-end projects. Vue-router can make it easier to build single-page applications. First, install vue-Router in the project with the following installation command:

//npm
npm install vue-router@next --save

//yarn
yarn add vue-router@next --save
Copy the code

After the installation is complete, create a router/index.ts folder in the SRC directory and add the following configuration:

import { createRouter, createWebHashHistory } from 'vue-router';

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    { path: '/', component: () => import('views/home.vue') }
  ]
});

export default router
Copy the code

We then introduce vue-Router in the main.ts file, as shown below.

import router from './router';
createApp(App).use(router).mount("#app");
Copy the code

2.2.2 Adding a Route page

To make it easier to hide, we add two more routing pages. Familiar with, create pages folder, the need to display the page to create complete. We then registered our new page on router/index.ts, as shown below.

routes: [
        {
            path: "/home",
            name: "Home",
            alias: "/",
            component: () => import("../pages/Home.vue")
        },
    ]
Copy the code

Next, let’s modify the app.vue code again, as shown below.

<template>
  <router-link to="/home">Home</router-link>
  <router-link to="/about">About</router-link>
  <router-view></router-view>
</template>

<script lang="ts">
import { defineComponent } from 'vue'

export default defineComponent({
  name: 'App'
})
</script>
Copy the code

Then start the service, you can see the configured page, and click to jump to the corresponding page.

2.3 integrated Vuex

Vuex is a state management mode developed specifically for vue.js applications. It uses centralized storage to manage the state of all components of an application and rules to ensure that the state changes in a predictable way. Vuex is also integrated into Vue’s official debugging tool devTools Extension (Opens New Window), providing advanced debugging functions such as zero-configuration time-travel debugging and state snapshot import and export. Before using Vuex, install the Vuex plug-in, as shown in the following figure.

//npm
npm install vuex@next --save

//yarn
yarn add vuex@next --save
Copy the code

After the installation is complete, you need to initialize Vuex. First, create a store/index.ts file and add the following code.

import { createStore } from "vuex";

const store = createStore({
  modules: {
    home: {
      namespaced: true,
      state: {
        count: 1
      },
      mutations: {
        add(state){
          state.count++;
        }
      }
    }
  }
})

export default store;
Copy the code

The above code implements a simple auto-add function. We then introduce Vuex in the main.js file.

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

import store from "./store";

const app = createApp(App);
app.use(store);
app.mount('#app');
Copy the code

With that done, let’s write a test code for Vuex to see if it works. The code to modify home.vue is as follows.

<template>
  <h1>Home Page</h1>
  <h2>{{count}}</h2>
  <button @click="handleClick">click</button>
</template>

<script lang="ts">
import { defineComponent, computed } from 'vue';
import { useStore } from 'vuex';

export default defineComponent({
  setup () {
    const store = useStore();
    const count = computed(() => store.state.home.count);
    const handleClick = () => {
      store.commit('home/add');
    };
    return {
      handleClick,
      count
    };
  }
})
</script>
Copy the code

The above code implements a simple auto-add function, the same as the default example project, but using Vuex.

2.4 integrated Eslint

ESLint is a code-checking tool that recognizes ECMAScript syntax and reports according to rules to avoid low-level errors and unify code styles. The following plugins are required to integrate Eslint: NPM

npm install eslint -D
npm install eslint-plugin-vue -D
npm install @vue/eslint-config-typescript -D
npm install @typescript-eslint/parser -D
npm install @typescript-eslint/eslint-plugin -D
npm install typescript -D
npm install prettier -D
npm install eslint-plugin-prettier -D
npm install @vue/eslint-config-prettier -D
Copy the code

Yarn way

yarn add eslint --dev
yarn add eslint-plugin-vue --dev
yarn add @vue/eslint-config-typescript --dev
yarn add @typescript-eslint/parser --dev
yarn add @typescript-eslint/eslint-plugin --dev
yarn add typescript --dev
yarn add prettier --dev
yarn add eslint-plugin-prettier --dev
yarn add @vue/eslint-config-prettier --dev
Copy the code

After the installation is complete, you also need to create an.eslintrc file in the root directory, as shown below.

{
  "root": true,
  "env": {
    "browser": true,
    "node": true,
    "es2021": true
  },
  "extends": [
    "plugin:vue/vue3-recommended",
    "eslint:recommended",
    "@vue/typescript/recommended"
  ],
  "parserOptions": {
    "ecmaVersion": 2021
  }
}
Copy the code

After adding the configuration rules, you also need to add the following commands to the scripts of the package.json file:

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

To verify the format, run YARN Lint. If there are many files, it will be very slow to verify. In this case, we will only verify the modified files at git commit time. You’ll need to use Lint-staged plug-ins.

//npm
npm install lint-staged -D
//yarn 
yarn add lint-staged --dev
Copy the code

Then, we modify package.json:

{
  "gitHooks": {
    "commit-msg": "node scripts/commitMessage.js",
    "pre-commit": "lint-staged"
  },
  "lint-staged": {
    "*.{ts,vue}": "eslint --fix"
  },
  "scripts": {
    "test:unit": "jest",
    "test:e2e": "cypress open",
    "test": "yarn test:unit && npx cypress run",
    "lint": "npx prettier -w -u . && eslint --ext .ts,.vue src/** --no-error-on-unmatched-pattern",
    "bea": "npx prettier -w -u ."   
  },
}
Copy the code

2.5 configuration alias

In the past, when using vue-CLI, we used @ to import certain files. Since Vite does not provide this configuration, we need to manually configure it so that we can use @ to import files quickly. First, we need to modify the configuration of vite.config.ts.

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

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: [
      {
        find: '@',
        replacement: '/src',
      },
      { find: 'views', replacement: '/src/views' },
      { find: 'components', replacement: '/src/components' },
    ]
  }
});
Copy the code

Then, we modify the tsconfig.json file as follows.

{ "compilerOptions": { "target": "esnext", "module": "esnext", "moduleResolution": "node", "strict": true, "jsx": "preserve", "sourceMap": true, "resolveJsonModule": true, "esModuleInterop": true, "lib": [" esnext ", "dom"], / / the following is a need to add the content "types" : [" vite/client ", "jest"], "baseUrl" : ""," paths ": {" @ / *" : ["src/*"] } }, "include": [ "src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue", ] }Copy the code

2.6 integrated element – plus

Element Plus is a Vue 3.0-based component library for developers, designers and product managers. It helps you quickly develop your website. If you have used Element-UI before, you can quickly transition to Element-Plus. In addition to Element-Plus, there are many UI frameworks that support Vue 3.0.

First, install element-plus in the root directory of your project with the following command:

npm install element-plus --save
Copy the code

2.6.1 to introduce element – plus

We can introduce the entire Element-Plus, or just a few components as needed. For all imports, just add the following code to main.js.

import { createApp } from 'vue'
import ElementPlus from 'element-plus';
i

const app = createApp(App)
app.use(ElementPlus)
app.mount('#app')
Copy the code

If you want to reduce the package size of your project, you just need to introduce the corresponding functional components. First, install the babel-plugin-Component plug-in, as shown below.

npm install babel-plugin-component --save
Copy the code

Then, modify the configuration of.babelrc.

{
  "plugins": [
    [
      "component",
      {
        "libraryName": "element-plus",
        "styleLibraryName": "theme-chalk"
      }
    ]
  ]
}
Copy the code

If we only need to introduce some components, such as Button and Select components, then we need to introduce the corresponding components in main.js, as shown below.

import { createApp } from 'vue' import { store, key } from './store'; import router from "./router"; import { ElButton, ElSelect } from 'element-plus'; import App from './App.vue'; import './index.css' const app = createApp(App) app.component(ElButton.name, ElButton); app.component(ElSelect.name, ElSelect); /* or * app.use(ElButton) * app.use(store, key) app.use(router) app.mount('#app')Copy the code

2.6.2 Adding a Configuration

With Element Plus, we can add a global configuration object. The object currently supports the size and zIndex fields. Size changes the default size of the component, and zIndex sets the initial Z-index of the pop-up. There are two different import modes: global import:

import { createApp } from 'vue'
import ElementPlus from 'element-plus';
import App from './App.vue';

const app = createApp(App)
app.use(ElementPlus, { size: 'small', zIndex: 3000 });
Copy the code

On demand:

import { createApp } from 'vue'
import { ElButton } from 'element-plus';
import App from './App.vue';

const app = createApp(App)
app.config.globalProperties.$ELEMENT = option
app.use(ElButton);
Copy the code

2.6.3 Configuring proxy and Alias

If you want to use the Alias alias configuration and proxy proxy configuration in Vite, you need to do the configuration separately in the vite.config.ts file.

import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import styleImport from 'vite-plugin-style-import' import path from 'path' // https://vitejs.dev/config/ export default defineConfig({ plugins: [ vue(), styleImport({ libs: [ { libraryName: 'element-plus', esModule: true, ensureStyleFile: true, resolveStyle: (name) => { return `element-plus/lib/theme-chalk/${name}.css`; }, resolveComponent: (name) = > {return ` element - plus/lib / ${name} `;},}]})], / * * * services in the production of basic public path. * @ default '/' * / base: '/', / * * * is associated with the "root" directory, build output will be placed on them. If the directory exists, it will be removed before the build. * @default 'dist' */ / outDir: 'dist', server: {// hostname: '0.0.0.0', host: "localhost", port: 3001, // // whether to automatically open in browser // open: true, // // whether to enable HTTPS // HTTPS: false, // // Server rendering // SSR: false, proxy: {'/ API ': { target: 'http://localhost:3333/', changeOrigin: true, ws: true, rewrite: (pathStr) = > pathStr. Replace ('/API ', ')},},}, resolve: {/ / import folder alias alias: {' @ ': path.resolve(__dirname, './src'), views: path.resolve(__dirname, './src/views'), components: path.resolve(__dirname, './src/components'), utils: path.resolve(__dirname, './src/utils'), less: path.resolve(__dirname, "./src/less"), assets: path.resolve(__dirname, "./src/assets"), com: path.resolve(__dirname, "./src/components"), store: path.resolve(__dirname, "./src/store"), mixins: path.resolve(__dirname, "./src/mixins") }, } })Copy the code

Of these, viet-plugin-style-import is a library that can introduce styles on demand.

Data request

Vue itself does not support Ajax calls, so if you need to perform network requests, you need to use tools such as SuperAgent and AXIos. However, it is Axios that is used a lot in Vue development.

//npm
npm insall axios -save

//yarn 
yarn add axios -save
Copy the code

Then, create a new request.ts and add the following code.

import axios from 'axios';

let request = axios.create({
    baseURL: 'http://localhost:3555/api'
})

export default request;
Copy the code

Then create a new index.ts to handle specific network requests, such as:

import request from "./axios"; Export const getUrl = () => {return request({URL: "/users/test" // request address})} export default {getUrl};Copy the code

Finally, call the interface defined above in our page code.

import { getUrl } from ".. /api/index" export default { setup() { const getUrls = async() =>{ const res = await getUrl() console.log(res) } onMounted(() => { getUrls() }) } }Copy the code

(End of text, thanks for reading)