On February 7, 2022, VUe3 became the default version of VUE, which means that vuE3 based ecosystem will be active in the front circle. Recently, the project is not too busy, so I used my spare time to build a complete vuE3 framework, from the rapid construction based on Vite to the specification. Let’s see, before the business code starts, Is there any work to be done?

Start fast

The VUe3 website provides an example of how to quickly build a VUE project using create-Vue scaffolding. Here we provide a way to build a project based on Vite.

viteSet up

Vite is a new tool for building a front-end framework that uses native ESM mechanisms, packages with Rollup, and builds on esBuild pre-build dependencies right out of the box. To create a project with Vite, the main steps are as follows:

  1. The command terminal displays a file directory, for example, D:/vueProject
  2. throughyarn create viteCommand to create a project.
  3. Select the project template to create, whether to use TS, and so on as prompted. Choose according to project needs.
  4. yarn create vite vite-of-vue --template vueYou can also use this command to generate projects. The directory is as follows. Unlike previous vue projects, index. HTML is in the root directory, not in the public directory. Besides, the main file is loaded in the index. HTML, which is in type/module format.

Second, project auxiliary tools

vue-devtools

Vue-devtools is a debugger for VUE projects. Through this tool, you can intuitively see changes in vUE related attributes, methods, and states. There are two ways to install it. The first way is to download it from a browser extension, but the other way is to download it from the Google Store. The second is to install the clone source code. The second method is highlighted here.

  1. Clone the code from Github to the local, vue-devtools git address
  2. Pull the code, open through the development tool, executeyarn installCommand to install project dependencies.
  3. Once installed, find it in Packagesshell-chromeThe project.
  4. Type chrome:// Extensions/into your browser, open developer mode, and drag shell-chrome into it. You can see the vue icon below.

volarTool use

As a perfect companion to Vue3, Volar has the same functionality as Vetur. As a plug-in for Vue, volar provides first-class support for typescript. Vue files are highlighted, style, template, scripts are visualized, and class references in sugar ref and style are supported. After all, the Volar is recommended by The University of Utah.

  1. In the vscode extension, searchvolarTo install the software.
  2. After installation, a small volar icon will appear at the top of the Vue file. Click the icon and you will see the surprise.

Development language, style, interface, routing configuration

The established VUE framework usually needs the support of the third party, such as the setting of development language, style selection, call interface tools, routing information configuration, etc. Once these are configured, they become more handy during development.

typescriptsupport

Github’s q4 programming language usage trends show that typescript continues to grow in popularity, as does its ability to detect types.

As we all know, supporting typescript is the bane of Vue2. In Vue3, Vite naturally supports the introduction of.ts files, which were introduced in the Quick Create project sectionvue-tsOnce installed, we can use TS to develop projects.

Style file support

In Vue3, you can import a. CSS file using @import. You can also import. Sass,. Less,.stylus files according to your coding habits. Vite provides built-in support for these files, so you don’t need to install plug-ins for them, but you do need to install preprocessor dependencies for them.

  1. npm add -D sassInstall SASS and SCSS dependencies.
  2. npm add -D lessInstall less dependencies.
  3. npm add -D stylusInstall the stylus and Styls dependencies.

After installation, in the vue file, defined by the lang=’****’ attribute, and just like the vue2 project, the scoped keyword is added to keep the CSS private. In addition to choosing the appropriate CSS preprocessor, the document structure of the style file can also be designed. Usually, we will separate common styles, third-party file styles, color properties, animation features and other independent folders to layer the CSS file, make it clearer and easier to maintain.

The routing configuration

Front-end projects usually control pages through different paths, and routes define the mapping relationship between paths and pages. Vue3 corresponds to vuE-Router 4, which is installed in the project and introduced in main.ts.

  1. yarn add vue-router --devInstalling a plug-in
  2. In main.ts, import is introduced.
  3. In main.ts, configure vue-router routing information and use app.use at the same time.
/ / introduce vueRouter
import * as VueRouter from "vue-router";
// Configure routing information
const router = VueRouter.createRouter({
  history: VueRouter.createWebHashHistory(),
  routes,
});
/ / use the call
app.use(router)
Copy the code

When importing routing files, hierarchical relationships need to be considered. If this is a project where multiple systems reuse the same login, 404, and personal information modification pages, you can configure these public pages in public routing files such as publicRouter files. The function page corresponding to the service system is configured in systemRouter. In this way, the hierarchy of routes is clear. I am also making a common component library synchronously. The public routing information will be extracted from the common component library. The service system only needs to configure service routes to complete the configuration of the entire routing information.

State management

In projects where data may be shared between different components or between different pages, use state management mechanisms. In terms of state management, the default version of VUe3 is VUex4. The installation and use of VUex4 are similar to that of VUe3. Pinia is a new state manager based on the Composition API and the successor to Vuex. The difference between Pinia and Vuex will be explained later in this article.

  1. yarn add pinia --devInstall pinia.
  2. In main.ts, import is introduced.
  3. Call app.use(createPinia()) in main.ts.

Pinia uses a two-step approach, defining a store and using a store

  1. defineStore()Create store, state, getters, actions are configured here.
  2. useStore()Use stores in components.
// Define store, in pinia mutaions have been removed
import { defineStore } from "pinia"
const useStore = defineStore("storeTest", {
	state: () = > ({
		count: 0.msg: "hello world",}).getters: {},
	actions: {},})export default useStore
Copy the code
// Use store in the.vue file and change the store contents
<script setup lang="ts">
    import useStore from ".. /stores/storeTest"
    const store = useStore()
    store.count += 1
    store.msg += " developers"
</script>
<template>
	<div>{{ store.count }}</div>
	<div>{{ store.msg }}</div>
</template>
Copy the code

Interface encapsulation

For interface calls, select AXIos. Vue3 incorporates AXIos in a slightly different way than VUe2. Vue3’s composition API is missing this and Prototype, so it needs to be used differently during development. Vue3 can either mount AXIos in global variables or use vuE-AXIos plug-ins to handle it. Of course, instead of injecting in main.ts, you could simply encapsulate all the interfaces in index.ts and call them in a vue file, but this approach lacks the concept of modularity and the code is verbose, so I’ll focus on the other two methods.

  • Mount to a global variableglobalPropertiesIn the
  1. yarn add axios --devInstall axios.
  2. In main.ts, mount Axios toglobalPropertiesIn the. GlobalProperties here is similar to vue.Prototype in VUe2.
  3. Use Axios in vue files.
// Mount axios in main.ts
import { createApp } from "vue"
import axios from "axios"
const app = createApp(App)
app.config.globalProperties.$axios = axios
Copy the code
// Used in vue files
import { ComponentInternalInstance, getCurrentInstance } from "vue"

const { appContext } = getCurrentInstance() as ComponentInternalInstance
console.log(appContext? .config.globalProperties.$axios)Copy the code

Note that we use typescript type assertions here. This is mainly because the getCurrentInstance() return type is null, so type assertions are used to circumvent it.

  • Use the vue-AXIos plug-in

Since the AXIos plug-in lacks the install method, the use plug-in in VUE must provide install. If you want to introduce it in the form of app.use, you can use the VUe-AXIos plug-in and provide Inject.

  1. yarn add vue-axios --devUse the command to install vue-axios, and note that axios is also required here
  2. Use it directly in main.tsapp.use(VueAxios, axios), the use ofprovideShare attributes.
  3. In the Vue file, passinjectUse.
// In main.ts, share axios with provide
import axios from "axios"
import VueAxios from "vue-axios"

app.use(VueAxios, axios)
app.provide("axios", app.config.globalProperties.axios)
Copy the code
// Vue file, use by inject
import { inject } from "vue"
const axios: any = inject("axios")
Copy the code

Four, specification

Why should specifications be considered when building a project? I think you’ve all encountered the problem that when we submit code, we often have conflicts because of the number of Spaces. This problem of different Spaces is often the result of personal code habits, and if there are no rules for code specifications in a project, you can spend a lot of time dealing with these unnecessary problems.

Code specifications usually fall into two categories, code quality and code style. Code quality tends to be verified for syntax, variable definition, etc. Code style tends to verify the format of code, while esLint is usually used to manage code quality in projects, prettierrc being used to unify code specifications.

The code quality specification ESLint

Eslint is primarily used to check javascript code, some might wonder, typescript itself checks javascript, so why use ESLint? We know that TS mainly checks code for type, while ESLint provides a unified code style in addition to type checking. So there’s actually some overlap in functionality, but ESLint adds something to the code style. How do you use ESLint in your project?

  1. You first need to install ESLint in your project path.yarn add eslint --dev
  2. Enter in the terminal./node_modules/.bin/eslint --initCommand, answer the questions as prompted, and select options that fit your project, such as vue or React, and what code style to use? When the question is answered, ESLint will recommend third-party dependencies that must be installed. After the installation is complete, the.eslintrc.js file is generated in the root path of the project. This file contains corresponding configuration properties, such as plugins that configure third-party plug-ins to be used, rules that provide rules to be defined, and extends that configure basic rules to be used.
  3. In the rules option of the.eslintrc.js file, you can customize your own rules.

With the selection in Step 2, ESLint will find the corresponding installation package and install it. The eslint-plugin-vue plugin is installed for vUE.

The eslint plugin is integrated with vscode. In older versions, since the esLint plugin does not check for.ts files by default, you need to configure the eslint.validate attribute in the.vscode/settings.js file to take effect. In the new version, however, no configuration is required, and the esLint. probe property already specifies the language types that esLint plugins need to validate.

// In earlier versions, the configuration is required
// .vscode/setting.json
{
    "eslint.validate": [
        "javascript"."javascriptreact"."vue"."typescript"]}Copy the code

You can also set the.eslintignore.js file to ignore some files that do not require code detection. For details about configuration rules, see the official website.

Code Style specification Prettier

Prettier’s website describes herself as an “attitude” code formatting tool, where formatting happens. It makes up for the lack of a complete code format in ESLint. Eslint +prettierrc, where one focuses on code quality, detecting potentially bug-causing code, and the other on code format, where the two combine to provide perfect code specification management for teams.

To deal with conflict

The yarn add prettier –dev command is used to install prettier. Because some format rules in ESLint may conflict with the rules in Prettier, eslint-config-prettier is installed to disable the configuration in ESLint that might cause conflicts. Install it using the yarn add eslint-config-prettier –dev command and configure it in the extends property. I need to put Prettier last here.

  // eslintrc.js configuration
  extends: [
    'plugin:vue/vue3-essential'.// eslint-plugin-vue rule extensions
    'airbnb-base'.'prettier',].Copy the code

When conflict is resolved, the rules in Prettier can be used completely, but prettier, where the rules are used, must be configured in a. Prettierrc. json file, where maintaining two sets of configuration files is messy. So we can use the eslint-plugin-prettier plug-in integrated into ESLint to use ESLint as a unified problem source for code detection.

  1. yarn add eslint-config-prettier --devInstall the plug-in.
  2. In.eslintrc.js, add the plugins attributeprettier.
  3. In Rules, it can be usedPrettier/rules“, adding the rule for prettier.

Code submission specification

In addition to the need for specifications when developing code, maintaining a common comment style when submitting code gives the team more control over problem location, code rollback, and so on. This paper introduces a management style based on the combination of CommLint, HusKY, Lint-Staged and Xconventional Changelog, wherein, Commlint defines commit specifications, HusKY mount execution actions, Lint-staged specifications for staging files, and Xcom-Changelog to generate Changelag.md change documents.

Define specificationcommitlint

The CommitLint tool can verify that the COMMIT format complies with the specification by installing the tools included with CommitLint to standardize the commit information.

  1. yarn add @commitlint/config-conventional @commitlint/cli --devRun this command to install dependencies.
  2. newcommitlint.config.jsFile, configuration specification, here directly use the default.
Git commit -m 
      
       (
       
        ?) : 
        
       
      
// scope Specifies the scope of the file being modified, such as SRC /views/ helloworld.vue
// subject: mandatory, specify the submission content
// type The type is as follows: Mandatory

module.exports = {
  extends: ["@commitlint/config-conventional"]};Copy the code
type meaning
build The main purpose is to modify the submission of the project build system
ci The main purpose is to modify the project to continue the integration process of submission
docs Document update
feat New features
fix Bug fix
perf Performance optimization
refactor Refactoring code (no new features, no bug fixes)
style Code changes that do not affect program logic (modifying whitespace characters, completing missing semicolons, etc.)
test Add test cases or update existing tests
revert Roll back some earlier commit
chore Other types that do not belong to the above types
Specifies when the specification is executedhusky

Once the specification information is defined, you can work with Husky to detect the code involved in git operations. Check out husky’s website for more information. We configure husky in package.json file. If husky failure occurs, check the following two aspects: 1. Check the sequence of git init operation and husky installation. 2. Check the version of YARN. Yarn 1 and YARN 2 are installed differently. This section describes how to install YARN 1.

  1. On the terminal, execute git init. Initialize as a Git project.
  2. Install the husky.yarn add husky --dev
  3. performnpm set-script prepare "husky install"The prepare command will be added to the scripts of the package.json file after executing this command.
  4. performyarn husky add .husky/pre-commit "yarn dev"Create a hook corresponding instruction. To test if Husky is working, I create a pre-commit hook and execute the command to start the project. After this step, the.husky folder is generated in the root directory.
  5. performgit add .husky/pre-commitAdd the added hooks to Git.
  6. performcommitCommand to check whether Husky is in effect.
The scope is refined to the staging arealint-staged

Lint-staged files can be detected from Git staging areas, which can be scaled down to files that need to be committed, ensuring that improper code can be prevented from entering the repository prior to push.

  1. yarn add lint-staged --devInstall the lint – staged.
  2. In the package.json file, configure Lint-staged information.
  3. In package.json, configure the corresponding Lint-staged directives.
  4. Lint-staged directives configured into pre-commit hooksyarn husky add .husky/pre-commit "yarn lint-staged". You can also click on the automatic file modification instructions in the.husky folder.

As you can see from the above figure, lint-Passage does not detect specific rules. Therefore, you need to add a COMMIT-MSG hook on which to configure commLint directives to ensure that prior to COMMITTING, lint-passage does not detect specific rules. Read the configuration rules in the commitlint.config.js file to examine the code.

  1. yarn husky add .husky/commit-msg "yarn commitlint --edit $1"Add the commit-msg hook.
  2. Pass the hookgit add Add the command to Git.
Generate change documentsconventional-changelog

The changelog. md change document can be automatically generated in coordination with Conventional Changelog after submitting according to the specifications for the team to record the changes.

  1. yarn add conventional-changelog-cli --devInstall dependencies.
  2. Configure the corresponding script."changelog": "conventional-changelog -p angular -i CHANGELOG.md -s -r 0"
  3. Create YARN Changelog and generate change files.

conclusion

After finish the above work, the project to be developed, in the development process, of course, also need to consider the current project is a component library, or a business library, if it is a component library, also need to project the plug-in makes extra work, also need to provide the plugin documentation, you can use VuePress offer similar static web sites the club’s official website, if is the business library, There is also a need to consider the packaging and deployment of the project, which will be covered in a later chapter.

Legacy items to be supplemented later: third-party component rewrite, custom component library, Mitt control event flow, project compression and deployment, static website generation.

Complete project structure diagram: