I. Introduction to Vite

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

Composition of 1.1 Vite

The Vite build tool consists of two parts:

  • A development server that provides rich built-in features such as module hot update (HMR) based on native ES modules.
  • A set of build directives that package your code using ROLLUP, and it is preconfigured to output static resources optimized for production.

In general, Vite wants to provide configuration out of the box, while its plug-in API and JavaScript API bring a high degree of extensibility. However, compared to the Vue-CLI configuration, a project built with Vite still has a lot of configuration that the developer needs 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: Browsers supported by default need to support the introduction of native ES modules via script tags. Old browsers can be supported via the official @vitejs/plugin-legacy plugin.

Two, environment construction

2.1 Create a Project

According to the Vite website, you can initialize a Vite project with NPM or yarn, and the Node.js version requires >= 12.0.0.

Use NPM mode

NPM init vite@latest project name

Use YARN

Yarn Create vite project name

In addition, you can specify the project name and template directly with additional command-line options. For example, to build a Vite + Vue project, the command looks like this:

# NPM 6.x NPM init @vitejs/app my-vue-app --template vue # 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 vue

After entering the command, follow the prompts. If your project needs TypeScript support, you can select Vue-ts when initializing the project. Once the project is created, you can see that the project directory structure created by Vite is very similar to the project directory structure created by Vue-CLI.

2.2 integrated Vue – the Router

2.2.1 Install and configure Vue-Router

As an essential routing tool for most projects and already used by most front-end projects, the Vue-Router makes it easier to build single-page applications. First, install the Vue-Router in your project with the following command:

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

//yarn
yarn add vue-router@next --save

After the installation is complete, create a folder in the SRC directory, router/index.ts, 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

Then, we introduce the Vue-router in the main.ts file, as shown below.

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

2.2.2 New routing page

To make it easier, we add two more routing pages. Familiar with, create the pages folder, the need to display the page to create a complete. Then, we register our newly added page at router/index.ts, as shown below.

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

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>

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

2.3 integrated Vuex

Vuex is a state management pattern 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 has integrated into DevTools Extension, the official debugging tool of Vue. It provides advanced debugging functions such as zero-configuration time-travel debugging, importing and exporting status snapshots, and so on.

Before using Vuex, you need to install the Vuex plug-in, as shown below.

//npm
npm install vuex@next --save

//yarn
yarn add vuex@next --save

After the installation is complete, you need to initialize Vuex first. 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;

The above code is used to implement a simple self – add function. Then, we 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');

With that done, let’s write a test code for Vuex to see if Vuex 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>

The above code implements a simple self-add function, which is the same as the default example project, except that we use Vuex.

2.4 integrated Eslint

ESLint is a code checker that recognizes ECMAScript syntax and reports it according to rules. It can be used to avoid low-level errors and to standardize code style. The following plug-ins are required to integrate ESLint:

NPM way

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

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

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
  }
}

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

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

Now you can run yarn lint, which can validate the format through ESLint. However, if you have a large number of files in yarn lint, you will have to verify all of them once, which can be very slow. In this case, ESLint only validates modified files when git commits, so you can do this. This requires the lint-staged plug-in.

//npm
npm install lint-staged -D
//yarn 
yarn add lint-staged --dev

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 ."   
  },
}

2.5 configuration alias

In the past, when we used Vue-CLI, we always used @ to import some files. Since Vite does not provide a similar configuration, we need to manually configure it so that we can continue to use the @ symbol 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' },
    ]
  }
});

Then, we modify the tsconfig.json file, as shown below.

{ "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", ] }

2.6 integrated element – plus

Element Plus is an open source component library for developers, designers and product managers based on VUE 3.0. it can help developers develop websites quickly. If you have used Element-UI, you can make the transition to Element-Plus quickly. In addition to Element-Plus, there are many other UI frameworks that support VUE 3.0.

To start, install Element-Plus in the root directory of your project with the following command:

npm install element-plus --save

2.6.1 to introduce element – plus

We can bring in the entire Element-Plus or just a few components as needed. To import them all, 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')

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

npm install babel-plugin-component --save

Then, modify the configuration of.babelrc.

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

If we only need to import a few components, such as the Button and Select components, then we need to import 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);

/* 或者
 * app.use(ElButton)
 * app.use(ElSelect)
 */

app.use(store, key)
app.use(router)
app.mount('#app')

2.6.2 Add configuration

With the introduction of Element Plus, we can add a global configuration object. This object currently supports the Size and ZIndex fields. Size is used to change the default size of the component, and zIndex sets the initial z-index of the pop-up. Here are two different ways to introduce it:

Global introduction:

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 });

Introducing 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);

2.6.3 Configure Proxy and Alias

If you want to use alias configuration and proxy proxy configuration in Vite, you need to do a separate configuration in the Vite.

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 deleted before the build. * @default 'dist' */ // outDir: 'dist', server: {// hostname: '0.0.0.0', host: "localhost", port: 3001, // // // open: true // open: true // HTTPS: false, render server // 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") }, } })

Among them, vite-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 a network request, you need tools such as SuperAgent and Axios. However, it is Axios that is used more in Vue development.

//npm
npm insall axios -save

//yarn 
yarn add axios -save

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;

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};

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() }) } }

How to Convert a Webpack Project to Vite