A,

Vite (French word for “fast”) is a new kind of front-end building tool

It was originally used with Vue3.0, and has since been adapted to various front-end projects, currently providing Vue, React, and Preact framework templates

Vite – a Web development tool developed by VUE author Yu Yuxi, which has the following features:

  • Quick cold start
  • Instant module hot update
  • True on-demand compilation

From the author’s comments on Weibo:

Vite, a development server based on browser native ES Imports. Parsing the imports in the browser, compiling and returning them on the server side on demand, bypassing the concept of packaging entirely, and making the server available on demand. Not only does it have Vue file support, it also handles hot updates, and the speed of hot updates does not slow down with the increase of modules. For production environments, the same code can be rollup. Although it is still rough, I think this direction has potential. If done well, it can completely solve the problem of changing a line of code and waiting for hot updates for half a day

It can be seen that the main feature of Vite is based on the browser native ES Module to develop, omit the packaging step, because what resources need to be directly introduced in the browser

Second, the construction 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.

2.1 Creating a Project

Use NPM mode

npm init vite@latestThe project nameCopy the code

Using Yarn Mode

Yarn Create Vite Project nameCopy the code

2.2 integrated Vue – the Router

Use NPM mode

npm install vue-router@next --save
Copy the code

Using Yarn Mode

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:

// index.js in the router directory
import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router'

const routes = [
  { path: '/'.component: () = > import('.. /components/Home.vue')]const router = createRouter({
  // Hash or history mode
  // history: createWebHashHistory(),
  history: createWebHistory(),
  routes
})
// Global route guard is the same as vue-Router3
// Route global front-guard
router.beforeEach((to,from,next) = >{
  console.log('Route global Front Guard', to, from);
  next()
})
// Route global post guard
router.afterEach((to,from,next) = >{
  console.log('Route global post Guard', to, from);
  next()
})

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

For demonstration purposes, let’s add two more routing pages. Familiar with, create views 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(".. /views/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.

Install vuex

npm install 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.ts 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 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

Against 2.4.1 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'
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.ts, 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.use(ElButton)
  app.use(ElSelect)

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

2.4.2 Adding the 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.4.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}`; },}]})],/** * The basic public path when serving in production. *@default '/' * /
  base: '/'./** * The directory associated with "root" where the build output will be placed. If the directory exists, it will be removed before the build. *@default 'dist'
  */
  // outDir: 'dist',
  server: {
    / / the hostname: '0.0.0.0',
    host: "localhost".port: 3001.// // Whether to open the browser automatically
    // 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 the folder alias
    alias: {
      The '@': 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.

2.5 integrated tailwindcss

The installation

npm install -D tailwindcss@latest postcss@latest autoprefixer@lates
Copy the code

Next, generate your tailwind.config.js and postcss.config.js files:

npx tailwindcss init -p
Copy the code

This will create a minimal tailwind.config.js file in your project root directory:

// tailwind.config.js
module.exports = {
  purge: [].darkMode: false.// or 'media' or 'class'
  theme: {
    extend: {},},variants: {
    extend: {},},plugins: [],}Copy the code

This will also create a postcss.config.js configuration file with tailwindcss and autoprefixer configured:

// postcss.config.js
module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},}},Copy the code

Configure Tailwind to remove style declarations that are not used in production

In your tailwind.config.js file, configure the Purge option to specify all the Pages and Components files so that Tailwind can tree-shake unused styles in a production build.

  // tailwind.config.js
  module.exports = {
-   purge: [],
+   purge: ['./index.html'.'./src/**/*.{vue,js,ts,jsx,tsx}'].darkMode: false.// or 'media' or 'class'
    theme: {
      extend: {},},variants: {
      extend: {},},plugins: [],}Copy the code

Replace the contents of your CSS with the Tailwind creation./ SRC /index.css file and use the @tailwind directive to include Tailwind’s base, components, and Utilities styles.

/* ./src/index.css */
@tailwind base;
@tailwind components;
@tailwind utilities;
Copy the code

Tailwind converts these instructions at build time into all the style files generated based on your configured design system.

Finally, make sure your CSS file is imported into your./ SRC /main.js file.

// src/main.js
import { createApp } from 'vue'
import App from './App.vue'
import './index.css'

createApp(App).mount('#app')
Copy the code

You have completed all the steps! Now, when you run NPM Run Dev, Tailwind CSS is ready for use in your Vue 3 and Vite projects.

2.6 integrated mock. Js

introduce

Mock. js official website: mockjs.com/

At present, most of the company’s projects are using the front and back end separation, back-end interface development and front end personnel are carried out simultaneously. The problem is that the back-end developer’s interface may not be written before the page needs to be rendered with a lot of data, and we, as the front-end, have no way to get the data. So the front end engineer needs to simulate the data provided by the back end according to the interface document to develop the page.

In this case, mock. js can automatically generate a large amount of simulated data on demand, instead of writing data one by one according to the format of the data according to the interface document. Mock. Js provides a large number of data types, including text, numbers, booleans, dates, mailboxes, links, images, colors, etc.

use

1) download

npm install mockjs
Copy the code

(2) the introduction of

Mock.js exposes a global Mock object, so we just need to introduce the Mock object into the file and call the Mock object’s methods

How CommonJS is introduced

/ / CommonJS introduction
let Mock = require(Mockjs) // Call mock.mock () to Mock data let data = mock.mock ({'list|1-10': [{'id|+1': 1}}); console.log(data);Copy the code

Introduction of ES6

// How ES6 is introduced
import Mock from 'mockjs'

let data = Mock.mock({
 The value of the attribute list is an array of 1 to 10 elements
'list|1-10': [{
        // Attribute id is an increment, starting at 1 and incrementing by 1 each time
  'id|+1': 1}}]);console.log(data);
Copy the code

Mock objects provide four methods, respectively

  • Mock.mock(),
  • Mock.setup()
  • Mock.valid,
  • Mock.toJSONSchema()

Mock. Mock () and Mock.Random.

(3) the Mock. Js specification

'list|1-10': [{
  'id|+1': 1
}]
Copy the code

The above code is called a data template and tells mock.js what data to generate. Each property in the data template consists of three parts: the property name, the generation rule, and the property value:

List is the attribute name in the data template. 1-10 for the generated rules (said to generate at least 1, up to 10 duplicate data) [{‘ id | + 1:1}] is the attribute value, attribute values can be nested in using the attribute name and generate rules.

For details, see github.com/nuysoft/Moc…

Mock.mock()

Mock. Mock () is used to generate Mock data from a data template. I use the following two methods of passing arguments:

Mock. Mock (template): Generates Mock data from the data template template

let data = Mock.mock({
data: {
  'products|10-20': [{
    name: 'mobile phone'.price: 1000}]}})console.log(data);
Copy the code

Mock. Mock (URL, template): Intercepts Ajax requests requesting urls and generates Mock data from the data template template

let data = Mock.mock('api/products' , {
data: {
  'products|10-20': [{
    name: 'mobile phone'.price: 1000}]}})// Use jquery Ajax to send requests
$.ajax({
  url: 'api/products'.type: 'GET'.success: function(res) {
    console.log(res); }})Copy the code

Mock.Random

Mock.Random is a utility class that mock. js provides for generating several types of data that are commonly used.

Generates a Boolean value

// use the @ placeholder
 let data = Mock.mock({
    data: {
      boolean: '@boolean'}})console.log(data);
Copy the code
// Use Mock.Random to call a function
  let data = Mock.mock({
    data: {
      boolean: Mock.Random.boolean()
    }
  })
  console.log(data);
Copy the code

Generate the date

 let data = Mock.mock({
    data: {
      date: Mock.Random.date('yyyy-MM-dd')}})console.log(data);
Copy the code

Mock.js supports rich date formatting customizations: github.com/nuysoft/Moc… Generate images

let data = Mock.mock({
    data: {
    // Use to generate highly customized image addresses
      imgURL: Mock.Random.image()
    }
  })
  console.log(data);
Copy the code

Generate the name

let data = Mock.mock({
    data: {
      // Generate an English name
      name: Mock.Random.name(),
      // Generate a Chinese name
      chineseName: Mock.Random.cname()
    }
  })
  console.log(data);
Copy the code

More data from the Mock.Random library: github.com/nuysoft/Moc…

Use Mockjs in Vite2 and Vue3 to simulate data

  1. Install mockjs
npm install mockjs --save-dev
Copy the code
  1. Install vite – plugin – the mock
npm i vite-plugin-mock cross-env -D
Copy the code

Plugin-mock: github.com/vbenjs/vite…

3. Set environment variables in package.json

{
    "scripts": {
        // Modifies the dev build script command
        "dev": "cross-env NODE_ENV=development vite"."build": "vite build"."serve": "vite preview"}}Copy the code

4. Add the MockJS plug-in to viet.config. js

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

export default defineConfig({
    plugins: [
        vue(),
        viteMockServe({
         mockPath: "./src/mock".supportTs: true     // If js is used, set supportTs to false})]})Copy the code

5. Create a mock folder in the root directory of the project and create index.ts to create the required data interface

// Just for example: return an array of names via a GET request
export default[{url: "/api/getUsers".method: "get".response: () = > {
            return {
                code: 0.message: "ok".data: ["tom"."jerry"],}}}]Copy the code
  1. Modify mock. Vue to request the interface and display the data
<template>
  <div v-for="(item,index) in users" :key="item">{{ index + 1 }}-{{ item }}</div>
</template>

<script lang="ts">
import { defineComponent, onMounted, ref } from "vue";
import axios from "axios"
import '.. /mock/index.ts'

export default defineComponent({
  setup() {
    let users = ref([])
    onMounted(() = > {
      axios.get(`/api/getUsers`).then(res= > {
        users.value = res.data.data
        console.log('users', users)
      }).catch(err= > {
        console.log(err)
      })
    })

    return { users }
  }
})
</script>
Copy the code