1, Code specification
1.1. Integrated editorconfig configuration
EditorConfig helps maintain a consistent coding style for multiple developers working on the same project on different IDE editors.
# http://editorconfig.org root = true [*] # Indicates that all documents are applicable charset = utf-8 # Set the file character set to utf-8 indent_style = space # Indent style (tab | space) indent_size = 2 # Indent Size end_of_line = lf # Control line feed type (lf | cr | crlf) trim_trailing_whitespace = true # Remove any white space characters at the beginning of the line insert_final_newline = true # Always insert a new line at the end of the file [*.md] # Indicates that the following rules apply only to md files max_line_length = off trim_trailing_whitespace = false
VSCode needs to install a plug-in: EditorConfig for VS Code
1.2. Using the prettier tool
Prettier is a powerful code formatting tool. It supports JavaScript, TypeScript, CSS, SCSS, Less, JSX, Angular, Vue, GraphQL, JSON, Markdown and other languages. Basically, it can handle all the file formats that can be used in the front end. It is the most popular code formatting tool at present.
1. Install prettier
npm install prettier -D
2. Configure the. Pretierrc file:
-
useTabs: use tab indentation or space indentation, and select false;
-
tabWidth: if tab is a space, select 2 spaces;
-
printWidth: the length of characters in a line. It is recommended to be 80. Some people like 100 or 120;
-
singleQuote: use single quotation marks or double quotation marks. Select true and use single quotation marks;
-
trailingComma: whether to add the trailing comma entered in multiple lines, set to none;
-
semi: whether to add a semicolon at the end of the statement. The default value is true. Selecting false means not to add a semicolon;
{ "useTabs": false, "tabWidth": 2, "printWidth": 80, "singleQuote": true, "trailingComma": "none", "semi": false }
3. Create. prettierignore ignore file
/dist/* .local .output.js /node_modules/** **/*.svg **/*.sh /public/*
4.VSCode needs to install the prettier plug-in
5. Test whether prettier is effective
-
Test 1: save the code in the code;
-
Test 2: configure the command of one-time modification;
Configure a script in package.json:
"prettier": "prettier --write ."
1.3. Test with ESLint
1. When we created the project, we selected ESLint, so Vue will help us configure the required ESLint environment by default.
2.VSCode needs to install ESLint plug-in:
3. Resolve the conflict between eslint and prettier:
Install plug-ins: (vue when creating a project, if prettier is selected, the two plug-ins will be installed automatically)
npm i eslint-plugin-prettier eslint-config-prettier -D
Add the prettier plug-in:
extends: [ "plugin:vue/vue3-essential", "eslint:recommended", "@vue/typescript/recommended", "@vue/prettier", "@vue/prettier/@typescript-eslint", 'plugin:prettier/recommended' ],
1.4. git Husky and eslint
Although we have asked the project to use eslint, we cannot guarantee that the team members will solve the problems in eslint before submitting the code:
-
That is, we want to ensure that the code in the code warehouse conforms to the eslint specification;
-
Then we need to verify the git commit command when the team member executes it. If it does not comply with the eslint specification, it will be repaired automatically through the specification;
So how do you do this? You can use the Husky tool:
-
husky is a git hook tool, which can help us trigger all stages of GIT submission: pre commit, commit MSG and pre push
How to use husky?
Here we can use the auto configuration command:
npx husky-init && npm install
Three things will be done here:
1. Install husky related dependencies:
2. Create a. husky folder under the project directory:
npx husky install
3. Add a script in package.json:
Next, we need to complete an operation: when commit ting, execute the lint script:
At this time, when we execute git commit, we will automatically lint verify the code.
1.5. git commit specification
1.5.1. Code submission style
Usually, our git commit will be submitted in a unified style, which can quickly locate the content submitted each time and facilitate version control later.
However, if it is troublesome to write these manually every time, we can use a tool: commit
-
Commit is a tool that helps us write a standard commit message;
1. Install Commitizen
npm install commitizen -D
2. Install CZ conventional changelog and initialize CZ conventional changelog:
npx commitizen init cz-conventional-changelog --save-dev --save-exact
This command will help us install CZ conventional changelog:
"cz-conventional-changelog":"^3.3.0",
And configure it in package.json:
"devDependencies": { "cz-conventional-changelog": "^2.1.0" }, "config": { "commitizen": { "path": "./node_modules/cz-conventional-changelog" } }
At this time, we need to use npx cz:
-
The first step is to select type, which is the type of this update
Type | effect |
---|---|
feat | New feature |
fix | Fix Bug(bug fix) |
docs | Document modification |
style | Code format modification (white space, formatting, missing semi colons, etc.) |
refactor | Code refactor |
perf | A code change that improves performance |
test | When adding missing tests |
build | Change project build or external dependencies (e.g. scopes: webpack, gulp, npm, etc.) |
ci | Change the configuration file of continuous integration software and the scripts command in package, such as scopes: Travis, Circle, etc |
chore | Change the build process or auxiliary tools (such as changing the test environment) |
revert | Code fallback |
Step 2: select the scope (SCOPE) of this modification
Step 3 select the submitted information
Step 4 submit detailed description information
Is the fifth step a major change
Step 6: whether an open issue is affected
We can also build a command in scripts to execute cz:
In the future, when we submit code, we need to use npx cz instead of npm run commit
1.5.2. Code submission verification
What if we standardize the submission style according to cz, but some colleagues still submit in a non-standard format through git commit?
-
We can restrict submission through commitlint;
1. Install @ commitlint / config conventional and @ commitlint/cli
npm i @commitlint/config-conventional @commitlint/cli -D
2. Create a commitlint.config.js file in the root directory and configure commitlint
module.exports = { extends: ['@commitlint/config-conventional'] }
3. Use husky to generate a commit MSG file to verify the submission information:
npx husky add .husky/commit-msg "npx --no-install commitlint --edit $1"
2, Third party library integration
2.1. vue.config.js configuration
vue.config.js can be configured in three ways:
-
Method 1: configure directly through the options provided to us by CLI:
-
For example, publicPath: configure the subdirectory of application deployment (the default is /, which is equivalent to deploying in https://www.my-app.com/ );
-
For example, outputDir: modify the output folder;
-
-
Method 2: modify the configuration of webpack through configureWebpack:
-
It can be an object and will be merged directly;
-
It can be a function that will receive a config. You can modify the configuration through config;
-
-
Method 3: modify the configuration of webpack through chainWebpack:
-
Is a function that receives a webpack-chain The config object can be used to modify the configuration;
-
const path = require('path') module.exports = { outputDir: './build', // configureWebpack: { // resolve: { // alias: { // views: '@/views' // } // } // } // configureWebpack: (config) => { // config.resolve.alias = { // '@': path.resolve(__dirname, 'src'), // views: '@/views' // } // }, chainWebpack: (config) => { config.resolve.alias.set('@', path.resolve(__dirname, 'src')).set('views', '@/views') } }
2.2. Vue router integration
Install the latest version of Vue Router:
npm install vue-router@next
To create a router object:
import { createRouter, createWebHashHistory } from 'vue-router' import { RouteRecordRaw } from 'vue-router' const routes: RouteRecordRaw[] = [ { path: '/', redirect: '/main' }, { path: '/main', component: () => import('../views/main/main.vue') }, { path: '/login', component: () => import('../views/login/login.vue') } ] const router = createRouter({ routes, history: createWebHashHistory() }) export default router
Installing router:
import router from './router' createApp(App).use(router).mount('#app')
Configure jump in App.vue:
<template> <div id="app"> <router-link to="/login">Sign in</router-link> <router-link to="/main">home page</router-link> <router-view></router-view> </div> </template>
2.3. vuex integration
Installation vuex:
npm install vuex@next
To create a store object:
import { createStore } from 'vuex' const store = createStore({ state() { return { name: 'coderwhy' } } }) export default store
Install store:
createApp(App).use(router).use(store).mount('#app')
Use in App.vue:
<h2>{{ $store.state.name }}</h2>
2.4. Element plus integration
Element Plus, a Vue 3.0-based desktop component library for developers, designers and product managers:
-
I believe many students have used element UI in Vue2, and element plus is a UI component library developed by element UI for vue3;
-
Its usage is the same as that of many other component libraries, so learn element plus, and others like ant design Vue, NaiveUI and VantUI are similar;
Installing element plus
npm install element-plus
2.4.1. Global import
One way to import element plus is global import, which means that all components and plug-ins will be automatically registered:
import ElementPlus from 'element-plus' import 'element-plus/dist/index.css' import router from './router' import store from './store' createApp(App).use(router).use(store).use(ElementPlus).mount('#app')
2.4.2. Local introduction
That is, a component is used to import a component during development:
Introduced in main.ts
//element on demand introduction import 'element-plus/dist/index.css' import { components } from './plugins/element-plus' for (const cpn of components) { app.component(cpn.name, cpn) } //element on demand introduction
Create the plugins folder under src and create the element-plus.ts file
import { ElButton, ElTable, ElAlert, ElAside, ElAutocomplete, ElAvatar, ElBacktop, ElBadge, ElContainer, ElHeader, ElMain } from 'element-plus' export const components = [ ElButton, ElTable, ElAlert, ElAside, ElAutocomplete, ElAvatar, ElBacktop, ElBadge, ElContainer, ElHeader, ElMain ]
2.5. axios integration
Install axios:
npm install axios
Encapsulating axios:
Create a service folder under src to centrally manage requests,
Encapsulate axios when creating request.ts
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios' export class Request { public static axiosInstance: AxiosInstance public static init() { // Create an axios instance this.axiosInstance = axios.create({ baseURL: '/api', timeout: 6000 }) // Initialize interceptor this.initInterceptors() return axios } // Initialize interceptor public static initInterceptors() { // Set post request header this.axiosInstance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded' /** * request interceptor * Before each request, if there is a token, the token is carried in the request header */ this.axiosInstance.interceptors.request.use( (config: AxiosRequestConfig) => { // In the login process control, the login status of the user is judged according to whether there is a token locally // However, even if the token exists, it may be expired, so the token is carried in each request header // The background judges the user's login status according to the carried token and returns the corresponding status code to us // if (config.headers.isJwt) { const token = localStorage.getItem('ACCESS_TOKEN') if (token) { ;(config as any).headers.Authorization = 'Bearer ' + token } // } return config }, (error: any) => { console.log(error) } ) // Response interceptor this.axiosInstance.interceptors.response.use( // Request succeeded (response: AxiosResponse) => { if (response.status === 200) { return response } else { Request.errorHandle(response) return response } }, // request was aborted (error: any) => { const { response } = error if (response) { // The request has been issued, but it is not in the range of 2xx Request.errorHandle(response) return Promise.reject(response.data) } else { // Deal with network disconnection // eg: update the network status of state when the request times out or is disconnected // network status controls the display and hiding of a global disconnection prompt component in app.vue // Refresh and re acquire data in the disconnection component will be described in the disconnection component // message.warn('network connection is abnormal, please try again later! ') console.log('Abnormal network connection,Please try again later!') } } ) } /** * http Handshake error * @param res Response callback, which performs different operations according to different responses */ private static errorHandle(res: any) { // Status code judgment switch (res.status) { case 401: break case 403: break case 404: // message.warn('requested resource does not exist ') console.log('The requested resource does not exist') break default: // message.warn('connection error ') console.log('Connection error') } } }
Create the http.ts file to store the requested path
import { Request } from './request' export function getUserList(parameter?: any) { return Request.axiosInstance({ url: '/users', method: 'get', data: parameter }) } export function home(parameter: any) { return Request.axiosInstance({ url: '/cxLogin', method: 'post', data: parameter }) }
2.6. VSCode configuration
{ "workbench.iconTheme": "vscode-great-icons", "editor.fontSize": 17, "eslint.migration.2_x": "off", "[javascript]": { "editor.defaultFormatter": "dbaeumer.vscode-eslint" }, "files.autoSave": "afterDelay", "editor.tabSize": 2, "terminal.integrated.fontSize": 16, "editor.renderWhitespace": "all", "editor.quickSuggestions": { "strings": true }, "debug.console.fontSize": 15, "window.zoomLevel": 1, "emmet.includeLanguages": { "javascript": "javascriptreact" }, "explorer.confirmDragAndDrop": false, "workbench.tree.indent": 16, "javascript.updateImportsOnFileMove.enabled": "always", "editor.wordWrap": "on", "path-intellisense.mappings": { "@": "${workspaceRoot}/src" }, "hediet.vscode-drawio.local-storage": "eyIuZHJhd2lvLWNvbmZpZyI6IntcImxhbmd1YWdlXCI6XCJcIixcImN1c3RvbUZvbnRzXCI6W10sXCJsaWJyYXJpZXNcIjpcImdlbmVyYWw7YmFzaWM7YXJyb3dzMjtmbG93Y2hhcnQ7ZXI7c2l0ZW1hcDt1bWw7YnBtbjt3ZWJpY29uc1wiLFwiY3VzdG9tTGlicmFyaWVzXCI6W1wiTC5zY3JhdGNocGFkXCJdLFwicGx1Z2luc1wiOltdLFwicmVjZW50Q29sb3JzXCI6W1wiRkYwMDAwXCIsXCIwMENDNjZcIixcIm5vbmVcIixcIkNDRTVGRlwiLFwiNTI1MjUyXCIsXCJGRjMzMzNcIixcIjMzMzMzM1wiLFwiMzMwMDAwXCIsXCIwMENDQ0NcIixcIkZGNjZCM1wiLFwiRkZGRkZGMDBcIl0sXCJmb3JtYXRXaWR0aFwiOjI0MCxcImNyZWF0ZVRhcmdldFwiOmZhbHNlLFwicGFnZUZvcm1hdFwiOntcInhcIjowLFwieVwiOjAsXCJ3aWR0aFwiOjExNjksXCJoZWlnaHRcIjoxNjU0fSxcInNlYXJjaFwiOnRydWUsXCJzaG93U3RhcnRTY3JlZW5cIjp0cnVlLFwiZ3JpZENvbG9yXCI6XCIjZDBkMGQwXCIsXCJkYXJrR3JpZENvbG9yXCI6XCIjNmU2ZTZlXCIsXCJhdXRvc2F2ZVwiOnRydWUsXCJyZXNpemVJbWFnZXNcIjpudWxsLFwib3BlbkNvdW50ZXJcIjowLFwidmVyc2lvblwiOjE4LFwidW5pdFwiOjEsXCJpc1J1bGVyT25cIjpmYWxzZSxcInVpXCI6XCJcIn0ifQ==", "hediet.vscode-drawio.theme": "Kennedy", "editor.fontFamily": "Source Code Pro, 'Courier New', monospace", "editor.smoothScrolling": true, "editor.formatOnSave": true, "editor.defaultFormatter": "esbenp.prettier-vscode", "workbench.colorTheme": "Atom One Dark", "vetur.completion.autoImport": false, "security.workspace.trust.untrustedFiles": "open", "eslint.lintTask.enable": true, "eslint.alwaysShowStatus": true, "editor.codeActionsOnSave": { "source.fixAll.eslint": true } }