What is the Vite

Vite (French for “fast”, pronounced /vit/, similar to veet) is a new front-end build tool. You can think of it as a combination of out-of-the-box development server and packaging tools, but lighter and faster. Vite leverages the browser’s native ES module support and tools compiled into native languages such as EsBuild to provide a fast and modern development experience.

The release of Vite2.0 brings build support for lower-version browsers that can be put into production.

Initialize the project

# npm 6.x
npm init @vitejs/app my-vue-app --template vue-ts

#NPM 7+, requires additional double lines:
npm init @vitejs/app my-vue-app -- --template vue-ts
Copy the code

I chose Vue3 + TypeScript template initialization (More templates), when the template is loaded, go to the project directory as prompted, load the dependencies, and try to run the project.

Less-css preprocessor

npm i less -D
Copy the code

vue-router

  1. Load the vue – router4. X
npm i vue-router@4
Copy the code
  1. Create router/index.ts in the SRC directory and write the route configuration.
import {createRouter, createWebHashHistory, RouteRecordRaw} from 'vue-router';
import Home from '.. /views/Home.vue';

const routes: Array<RouteRecordRaw> = [ // Add type declarations to restrict configuration items to improve writing experience
    {
        path: '/'.name: 'Home'.component: Home,
    }
];

const router = createRouter({
    history: createWebHashHistory(),
    routes,
});

export default router;
Copy the code
  1. Import the route configuration in main.ts
import {createApp} from 'vue';
import router from './router'; // <---
import App from './App.vue';

createApp(App)
    .use(router) // <---
    .mount('#app');
Copy the code
  1. Create views/ home. vue in the SRC directory and write the content you want to display on the Home page.
<template>
  <img alt="Vue logo" src=".. /assets/logo.png" />
  <p>Home: Hello Vue 3 + TypeScript + Vite</p>
</template>

<script lang="ts">
import {defineComponent} from 'vue';export default defineComponent({
  name: 'Home'
})
</script>
Copy the code
  1. App.vue can then be used as a carrier for reouter-view, for example, as follows.
<template>
    <div id="nav">
        <router-link to="/">Home</router-link>
    </div>
    <router-view/>
</template>

<style lang="less">
#app {
  text-align: center;
  color: #2c3e50;
}

#nav {
  padding: 30px;

  a {
    font-weight: bold;
    color: #2c3e50;

    &.router-link-exact-active {
      color: #42b983; }}}</style>
Copy the code
  1. Run the project, and the Home page is rendered.

vuex

  1. Load the vuex4. X
npm i vuex@4
Copy the code
  1. Create store/index.ts in the SRC directory and write the status manager configuration.
import {InjectionKey} from 'vue';
import {createStore, Store} from 'vuex';
import user, {State as UserState} from './user';

// Summarize the State types for each module
export interface State {
    user: UserState;
}

export const key: InjectionKey<Store<State>> = Symbol(a);constdebug = process.env.NODE_ENV ! = ='production';

export const store = createStore<State>({
    modules: {user},
    strict: debug
});
// Inject a $store type declaration into the component
declare module '@vue/runtime-core' {
    interface ComponentCustomProperties {
        $store: Store<State>; }}Copy the code
  1. Modularization, new store/user.ts user module.
import {Module} from 'vuex';
import {State as RootState} from './index';

export interface State {
    age: number;
}
export default {
    namespaced: true.actions: {
        addAge({commit, state}, value: number) {
            commit('SET_USER_AGE', state.age + value); }},getters: {
        age: state= > state.age
    },
    mutations: {
        SET_USER_AGE(state, age: State['age']){ state.age = age; }},state: {
        age: 5}}as Module<State, RootState>;
Copy the code
  1. Introduce store in main.ts.
import {createApp} from 'vue';
import router from './router';
import {store, key} from './store'; // <---
import App from './App.vue';

createApp(App)
    .use(store, key) // <---
    .use(router)
    .mount('#app')
Copy the code
  1. Call the state of the User module in home.vue to run the project again.
<template>
    <! -... -->
    <p>
        <span>vuex user/age: {{age}}</span>
        <button @click="addAge">age++</button>
    </p>
</template>
<script lang="ts">
import {defineComponent, computed} from 'vue';
import {useStore} from 'vuex';
import {key} from '.. /store';

export default defineComponent({
  name: 'Home'.setup() {
    const store = useStore(key); // Call Vuex's Composition API to get the store, equivalent to $store
    const age = computed(() = > store.getters['user/age']);
    const addAge = () = > store.dispatch('user/addAge'.1);
    return{age,addAge}; }})</script>
Copy the code

ant-design-vue

  1. Load the ant – design – vue2. X
npm i ant-design-vue@next

#Handle plug-ins loaded on demand
npm i vite-plugin-importer -D
Copy the code
  1. In viet.config. ts, add viet-plugin-importer
import {defineConfig} from 'vite';
import vue from '@vitejs/plugin-vue';
import importerPlugin from 'vite-plugin-importer'; // <---

// https://vitejs.dev/config/
export default defineConfig({
    css: {
        preprocessorOptions: {
            less: {
                javascriptEnabled: true // To use antD's less style, turn it on}}},plugins: [
        vue(),
        importerPlugin({ // <---
            libraryName: "ant-design-vue".libraryDirectory: "es".style: true // less]}}));Copy the code
  1. Create config/antd.config.ts in the SRC directory to import antD globally.
import {Plugin} from 'vue';
import {Button, message} from 'ant-design-vue';

const antdInstall: Plugin = function (app) { // Declare middleware exposure, more elegant call
    app.use(Button);
    app.config.globalProperties.$message = message;
};
export default antdInstall;
declare module '@vue/runtime-core' {
    interface ComponentCustomProperties {
        $message: typeofmessage; }}Copy the code
  1. Introduce antD configuration in main.ts.
import {createApp} from 'vue';
import antd from './config/antd.config'; // <---
import router from './router';
import {store, key} from './store';
import App from './App.vue';

createApp(App)
    .use(store, key)
    .use(router)
    .use(antd) // <---
    .mount('#app')
Copy the code
  1. Using ANTD’s Button component in home.vue, run the project again.
<template>
    <! -... -->
    <a-button type="primary" @click="addAge">age++</a-button>
    <! -... -->
</template>

Copy the code

Compatible with earlier versions of browsers

  1. Load the @ vitejs/plugin – legacy
npm i @vitejs/plugin-legacy -D
Copy the code
  1. Enable @vitejs/plugin-legacy in viet.config. ts
import {defineConfig} from 'vite';
// ...
import legacyPlugin from '@vitejs/plugin-legacy';

// https://vitejs.dev/config/
export default defineConfig({
    // ...
    plugins: [
        // ...
        legacyPlugin({
            targets: ['defaults'.'not IE 11']]}}));Copy the code

When you build like this, Vite compiles the artifacts according to the Targets configuration.

internationalization

  1. Load the vue – i18n
npm i vue-i18n@next
Copy the code
  1. Create config/i18n.config.ts in the SRC directory and configure the multi-language copy file.
import {createI18n} from 'vue-i18n';

const messages = {
    cn: {
        message: {
            hello: 'Hello China'}},en: {
        message: {
            hello: 'Hello World'}}};export default createI18n({
    locale: 'en'.fallbackLocale: 'en',
    messages
});
Copy the code
  1. Introduce internationalization configuration in main.ts.
import {createApp} from 'vue';
// ...
import i18n from 'config/i18n.config';
import App from './App.vue';

createApp(App)
    .use(i18n)
    // ...
    .mount('#app');
Copy the code
  1. Call the language output function at home.vue to run the project again.
<template>
    <! -... -->
    <p>{{$t('message.hello')}}</p>
    <p>{{t('message.hello')}}</p>
</template>
<script lang="ts">
import {defineComponent} from 'vue';
import {useI18n} from 'vue-i18n';

export default defineComponent({
  name: 'Home'.setup() {
    // ...
    return {
        // ...
        t: useI18n().t }; }})</script>
Copy the code

Use either the globally injected $t or useI18n().t, which is responsible for getting copywriting output in setup.

The alias

  1. Configure the mapping of aliases in the vue file in vite.config.ts.
import {defineConfig} from 'vite';
// ...

// https://vitejs.dev/config/
export default defineConfig({
    // ...
    resolve: {
        alias: {
            The '@': '/src'.'assets': '/src/assets'.'components': '/src/components'.'config': '/src/config'.'router': '/src/router'.'store': '/src/store'.'views': '/src/views'}}});Copy the code
  1. Configure the mapping of aliases in ts files in ts.config.json.
{
    "compilerOptions": {
        // ...
        "paths": {
          "@ / *": ["src/*"]."*": ["*"."src/*"]},// ...}}Copy the code

eslint

Integrate an ESLint into your project to keep your code style consistent when multiple people collaborate.

  1. Load the vite – plugin – eslint
npm install vite-plugin-eslint --save-dev
Copy the code

Vite is compatible with rollup, so @rollup/ plugin-esLint is theoretically possible.

  1. Enable viet-plugin-eslint in viet.config. ts
import {defineConfig} from 'vite';
// ...
import eslintPlugin from 'vite-plugin-eslint';

// https://vitejs.dev/config/
export default defineConfig({
    // ...
    plugins: [
        // ...
        eslintPlugin({
            cache: false.fix: false.include: [
                'src/**/*.ts'.'src/**/*.d.ts'.'src/**/*.tsx'.'src/**/*.vue'.'tests/**/*.ts'.'tests/**/*.tsx'].exclude: [
                'node_modules']]}}));Copy the code

The above configuration disables caching, and the include and exclude ranges have been modified as required (see ts.config.json for the default range configuration).

  1. As with any project using ESLint, you need an eslintrc.js file in the root directory that defines rules for code specification checking (Here is eslintrc.js from vue-CLI initialization project).
module.exports = {
  root: true.env: {
    node: true
  },
  'extends': [
    'plugin:vue/vue3-essential'.'eslint:recommended'.'@vue/typescript/recommended'].parserOptions: {
    ecmaVersion: 2020
  },
  rules: {
    'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off'.'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off'}}Copy the code
  1. The above configuration uses some external plug-ins that need to be loaded separately.
npm install eslint eslint-plugin-vue  --save-dev
npm install @typescript-eslint/eslint-plugin @typescript-eslint/parser --save-dev
npm install @vue/eslint-config-typescript --save-dev
Copy the code
  1. The rules in the eslintrc.js file can be expanded to suit your needs.

conclusion

  • Each dependency has a guide and detailed documentation on its official website, which can be set up in steps.
  • Most dependencies have typescript implementations, and using the type constraints provided in the dependencies gives you good hints and checks when configuring them.
  • Vite is implemented using rollup and can be extended using the rollup plug-in.