Quick start for Vite development

xiangzhihong
中文

1. Introduction to Vite

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

1.1 Vite composition

The Vite build tool consists of two parts:

  • A development server, which provides rich built-in functions based on native ES modules, such as module hot update (HMR) .
  • A set of build instructions, it uses Rollup package your code, and it is pre-configured to output optimized static resources for production environments.

In general, Vite hopes to provide out-of-the-box configuration, while its plug-in API and JavaScript API bring a high degree of scalability. However, compared to the Vue-cli configuration, the project built by Vite still has a lot of configuration that needs to be handled by the developer.

1.2 Browser support

Two, environment construction

2.1 Create a project

According to the introduction of the Vite official website, we can use npm or yarn to initialize the Vite project, and the Node.js version needs to be >= 12.0.0.

use NPM method

npm init vite@latest 项目名

uses Yarn method

yarn create vite 项目名

In addition, you can also directly specify the project name and template through additional command line options. For example, to build a Vite + Vue project, the command is as follows:

# 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, just follow the prompts. If the project needs to support TypeScript, you can choose vue-ts when you initialize the project. After the project is created, you can find that the project created by Vite is actually similar to the project directory structure created by Vue-cli.

2.2 Integrate Vue-Router

2.2.1 Install and configure Vue-Router

As an indispensable routing tool for most projects, Vue-Router 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, the installation command is as follows:

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

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

After the installation is complete, create a folder router/index.ts in the src directory, and then 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 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 to cover up, we add two more routing pages. Familiar with, create the pages folder, and create the pages that need to be displayed. Then, we register our new page in router/index.ts, as shown below.

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

Next, let's modify the code of App.vue, 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 to jump to the corresponding page.

2.3 Integrate Vuex

Vuex is a state management mode specially developed for Vue.js applications. It uses centralized storage to manage the state of all components of the application, and uses corresponding rules to ensure that the state changes in a predictable manner. 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, state snapshot import and export, etc.

Before using Vuex, you need to install the Vuex plugin, 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 function of the above code is to realize a simple self-adding 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');

After completing the above operations, let's write a test code for Vuex to see if Vuex is effective. Modify the code of Home.vue 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-adding function, which has the same effect as the default sample project, except that we use Vuex.

2.4 Integrate Eslint

ESLint is a code inspection tool used to identify ECMAScript syntax and report according to the rules. Using it can avoid low-level errors and unify the code style. To integrate Eslint, you need to install the following plug-ins:

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 method

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 follows.

{
  "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 commands in the scripts of the package.json file:

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

Next, just run yarn lint , and the format can be verified through eslint. However, when we execute yarn lint , all files will be verified once. If there are many files, the verification speed will be very slow. At this time, we generally only modify the changes when git commits. The file is verified by eslint, then we can do so.
Then you need to use the lint-staged plugin.

//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 Configure alias

When using vue-cli in the past, we always used @ to import certain files. Since Vite does not provide similar configuration, we need to configure it manually before we can continue to use the @ symbol to quickly import files. 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 are modifying 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"],
   
   //以下为需要添加内容
    "types": ["vite/client", "jest"],
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    } 
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.d.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
  ]
}

2.6 Integrate element-plus

Element Plus is a set of Vue 3.0-based component libraries for developers, designers and product managers produced by the big front-end team of Ele.me. It can help developers develop websites quickly. If you have used element-ui, Then 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 the project, the command is as follows:

npm install element-plus --save

2.6.1 Introducing element-plus

We can introduce the entire element-plus, or only part of the components as needed. If it is all imported, 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 the project, you only need to introduce the corresponding functional components. First, install the babel-plugin-component plugin as shown below.

npm install babel-plugin-component --save

Then, modify the configuration content of .babelrc.

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

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

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

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

2.6.2 Add configuration

After introducing Element Plus, we can add a global configuration object. The object currently supports size and zIndex fields. size is used to change the default size of the component, and zIndex sets the initial z-index of the bullet frame. The following are two different ways of introduction:

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

introduced 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 configuration in Vite, you need to configure it 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}`;
          },
        }
      ]
    })
  ],

  /**
   * 在生产中服务时的基本公共路径。
   * @default '/'
   */
  base: './',
  /**
  * 与“根”相关的目录,构建输出将放在其中。如果目录存在,它将在构建之前被删除。
  * @default 'dist'
  */
  // outDir: 'dist',
  server: {
    // hostname: '0.0.0.0',
    host: "localhost",
    port: 3001,
    // // 是否自动在浏览器打开
    // open: true,
    // // 是否开启 https
    // https: false,
    // // 服务端渲染
    // ssr: false,
    proxy: {
      '/api': {
        target: 'http://localhost:3333/',
        changeOrigin: true,
        ws: true,
        rewrite: (pathStr) => pathStr.replace('/api', '')
      },
    },
  },
  resolve: {
    // 导入文件夹别名
    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 import styles on demand.

Three, data request

Vue itself does not support ajax calls. If you need to perform network requests, you need to use some tools, such as superagent and axios. However, axios is the most used for 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 process specific network requests, such as:

import request from "./axios";

export const getUrl = () => {
    return request({
        url: "/users/test" // 请求地址
    })
}

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

Next article: How to transfer Webpack project to Vite

阅读 915

著有《React Native移动开发实战》1,2、《Kotlin入门与实战》《Weex跨平台开发实战》、《Flutter跨平台...

4.1k 声望
12.2k 粉丝
0 条评论
你知道吗?

著有《React Native移动开发实战》1,2、《Kotlin入门与实战》《Weex跨平台开发实战》、《Flutter跨平台...

4.1k 声望
12.2k 粉丝
宣传栏