SoFunction
Updated on 2025-04-03

Detailed explanation of Vite development environment construction

​Vite​​​It's so popular now, and many friends may not have used it yet​Vite​​​, but I believe most of my friends are already using it​Vite​​​, because it is so fragrant, is there any. There may be a lot of things during use​Vite​​​Not configured, not like​Vue-cli​​The configuration is very thorough, so today I will talk about how to configure the development environment. The main points involved are as follows:

  • TypeScript
  • Vuex
  • Vue-Router
  • E2E
  • Cypress
  • Test unit
  • Jest
  • vtu
  • Eslint + Perttite
  • verify git commit message
  • CI
  • alias

Vite initialization project

Use it first before you start​Vite​Create a project, if your friend has already met​Vite​​After having a certain understanding, you can skip it. According to​Vite​​Official website introduction can be used​npm​​or​yarn​​To create a project.

​Using NPM:

npm init vite@latest

Using Yarn:

yarn create vite

Using PNPM:

pnpx create-vite

After entering the command, follow the prompts, because the project needs to support it​TypeScript​So I chose here​vue-ts​​​. After creation​Vite​​​It will help us create the project well and you can discover it​Vite​​​The created project is actually and uses​Vue-cli​​The project directory structure created is actually similar, so I won’t go into details here.

Integrated Vue-Router

​Vue-Router​It is one of the most indispensable tools in most projects.​Vue-Router​​Make it easier to build single-page applications. The included functions are:

  • Nested routes/view charts
  • Modular, component-based routing configuration
  • Routing parameters, queries, wildcards
  • View transition effect based on transition system
  • Fine-grained navigation control
  • Links with automatic activation of CSS class
  • HTML5 history mode or hash mode, automatically downgraded in IE9
  • Custom scrollbar behavior

The above is taken fromVue-router official website​

Install Vue-Router:

Using NPM:

npm install vue-router@next --save

Using Yarn:

yarn add vue-router@next --save

After the installation is completed,​src​Create folders in the directory​router/​, after creation is completed, you need to​Vue-Router​​Mind-by​Vue-Router​​Processing initialization configuration. We temporarily put the initialization work aside and need to create it first​pages​​Folder, create the pages to be displayed.

After the creation is completed, the next step is to improve​router/​The initialization of the file in ​ works:

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

const router = createRouter({
history: createWebHashHistory(),
routes: [
{
path: "/home",
name: "Home",
alias: "/",
component: () => import("../pages/")
},
{
path: "/about",
name: "About",
component: () => import("../pages/")
}
]
})

export default router;

Next in​​Integration in files​Vue-Router​​:

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

import router from "./router";

const app = createApp(App);
(router);
('#app');

Test it, modify it here​​​code, test whether our route can be used normally.

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

Next, start the service and you can see the configured page, indicating that the configured route has taken effect. ​​Good Job​​, it's really good~~~

Integrated Vuex

​Vuex​Yes​Vue​The supported state management tools also play a great role in actual application. When data flow between multiple components becomes very difficult, it is necessary to centrally manage states.​Vuex​The state storage of ​is responsive. When​Vue​Components from​store​When reading the status in ​, if​store​If the state in ​ changes, the corresponding components will be updated efficiently accordingly.

Install Vuex:

Using NPM:

npm install vuex@next --save

Using Yarn:

yarn add vuex@next --save

After the installation is complete, add​store/​To initialize​Vuex​​. It should be noted that the following example uses​Vuex​​namespace. It may be relatively common to use namespaces in actual projects to avoid variable pollution when performing state management.

import { createStore } from "vuex";

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

export default store;

Integrate to​Vue​​Medium:

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

import router from "./router";
import store from "./store";

const app = createApp(App);
(router);
(store);
('#app');

Now​Vuex​It has been integrated into​Vue​In order to ensure integration​Vuex​​is effective, then test this:

pages/

<template>
<h1>Home</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(() => );
const handleClick = () => {
('home/add');
};
return {
handleClick,
count
};
}
})
</script>

When you click the button, you can find​count​The value also increases with each click, then​store​​​It can be used normally. ​​Good Job​​, it's really good~~~

Integrated Git Submission Verification

When developing a project, it may not be developed by one person, but may be developed by multiple people. Therefore, as a standard automation, for​Git​​When submitting, there must be some fixed and significant formats to regulate our project developers, and at this time, some tools need to be used for constraints.

Installation-related dependencies:

Using NPM:

npm install yorkie -D
npm install chalk -D

Using Yarn:

yarn add yorkie --dev
yarn add chalk --dev

After installing the dependencies,​yorkie​After that, it needs to be configured in​​Add fields to:

{
"gitHooks": {
"commit-msg": "node scripts/"
}
}

In the above configuration, a​js​File, then this​js​​The file is the verification of the submitted content.

scripts/

const chalk = require('chalk')
const msgPath = .GIT_PARAMS
const msg = require('fs').readFileSync(msgPath, 'utf-8').trim()

const commitRE = /^(revert: )?(feat|fix|docs|dx|style|refactor|perf|test|workflow|build|ci|chore|types|wip|release)(\(.+\))?(.{1,10})?: .{1,50}/
const mergeRe = /^(Merge pull request|Merge branch)/

if (!(msg)) {
if (!(msg)) {
(msg)
(
` ${(' ERROR ')} ${(
`invalid commit message format.`,
)}\n\n` +
(
` Proper commit message format is required for automated changelog generation. Examples:\n\n`,
) +
` ${(`feat(compiler): add 'comments' option`)}\n` +
` ${(
`fix(v-model): handle events on blur (close #28)`,
)}\n\n` +
(
` See /vuejs/vue-next/blob/master/.github/ for more details.\n`,
),
)
(1)
}
}

Integrated Eslint

​Eslint​​It is a very good tool for team development, and it can be used according to​Eslint​The configuration of ​constrains the style of the developer's code and the writing format.

Installation-related dependencies:

Using 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

Using Yarn:

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 configuration and installation are completed, you still need to​eslint​​Configuration, create in the root directory​.eslintrc​​:

.eslintrc

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

The configuration items have been added, how to run the configured ones​eslint​What about? Next, you need to​​Add commands to:

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

Next run​yarn lint​That's fine, you can pass​eslint​​The format verification has been completed. What is the problem now? I am executing it​yarn lint​​When all the files are checked once, this is not what we hoped. If there are many files, the speed will be very slow. So is there any way to just go?​git​​Make a modified file when submitting​eslint​​What about verification?

Installation-related dependencies:

Using NPM:

npm install lint-staged -D

Using Yarn:

yarn add lint-staged --dev

Modify​​​:

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

Configure alias

In use​cli​Always use it when​@​​To import certain files, because​Vite​​No similar configuration is provided, so we need to manually configure it to continue using it​​@​​Symbols to quickly introduce files.

Modify​​​:

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

// /config/
export default defineConfig({
plugins: [vue()],
resolve: {
alias: [
{
find: '@',
replacement: '/src',
},
{ find: 'views', replacement: '/src/views' },
{ find: 'components', replacement: '/src/components' },
]
}
});

Modify​​​:

{
"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/**/*.",
"src/**/*.tsx",
"src/**/*.vue",
"tests/unit"
]
}

To ensure that it can also be used in unit tests​@​​Introduced​src​The following file needs to be​​​Configuration modification:

Modify​​​:

 = {
transform: {
'^.+\\.vue$': 'vue-jest',
'^.+\\.jsx?$': 'babel-jest',
'^.+\\.tsx?$': 'ts-jest',
},
testMatch: ['**/?(*.)+(test).[jt]s?(x)'],
moduleNameMapper: {
"@/(.*)$": "<rootDir>/src/$1"
}
};

This is the end of this article about the detailed explanation of Vite development environment construction. For more related content on Vite development environment construction, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!