Build vuE3 + Vite + Vant mobile terminal project
As VUE3 became more and more mature, with the advent of Vite. So I recently tried to build a mobile project with Vite +vue3, so record the process. Small partners in need can be used as a reference to build, you can take many detours.
Initialize the project
Compatibility: Vite requires node.js version >= 12.0.0.
Vite provides initialization for different tools
1. Initialize through NPM
NPM init vite@latest Copies the codeCopy the code
2. Use Yarn
Yarn Create vite Copies the codeCopy the code
3. Through PNPM
PNPM DLX create-vite copies the codeCopy the code
Take NPM as an example:
1. Project Name
2. Choose the frame
3. Whether to introduce TS
4, complete
By specifying a specific template
Specify the project name and the template you want to use directly with additional command-line options. For example, to build a Vite + Vue project, run the command:
# NPM 6.x NPM init vite@latest my-vue-app --template vue # NPM 7+, requires additional double lines: NPM init vite@latest my-vue-app -- --template vue # yarn yarn create vite my-vue-app --template vue copy codeCopy the code
Supported template presets include:
vanilla
vanilla-ts
vue
vue-ts
react
react-ts
preact
preact-ts
lit-element
lit-element-ts
svelte
svelte-ts
See create-vite for more details on each template.
Introducing ESLint to improve code quality
Install ESLint and related plugins
NPM install eslint eslint-plugin-vue babel-eslint -d copies codeCopy the code
Create one in the root directory.eslintrc.js
File that defines esLint rules
// .eslintrc.js module.exports = { root: true, parserOptions: { parser: 'babel-eslint', sourceType: 'module' }, env: { browser: true, node: true, es6: true }, extends: [ 'plugin:vue/vue3-essential', 'eslint:recommended' ], // add your custom rules here rules: {// "off" or 0 - Close rule // "warn" or 1 - treat rule as a warning // "error" or 2 - Treat rule as an error // allow async-await 'generator-star-spacing': 'off', // 'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off', // allow debugger during development // 'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off', /** * best practices */ eqeqeq: 2, // Enforce === and! == 'default-case': 1, // Require switch statement with default branch 'no-else return': 1, // Disallow else block 'no-empty-function': 1, // disallow empty function' no-multi-spaces': 1, // disallow multiple Spaces radix: 1, // enforce cardinality arguments in parseInt() /** * variable declarations */ 'init-declarations': /** * ECMAScript6 */ 'arrow-spacing': ['error', {before: true, after: True}], // enforces the arrow function to use a space before and after the arrow 'no-var': 2, // disallows the var declaration variable 'object-type ': 2, // Require the object method name and attribute name to be short 'prefer-arrow-callback': 2, // require the callback function to use the arrow function 'prefer-const': // use const to declare variables that will not be modified after being declared 'prefer-rest-params': /** * style guide */ 'space-before-function-paren': 0, // Function names or function keywords must be spaced 'array-brack-spacing ': 0, // Comma-dangle ': 2 must be spaced within array brackets, // disallow trailing comma 'eol-last': {beforeColon: false, afterColon: }], // spacing must be 'keyword-spacing': ['error', {before: true, after: True}], // disallow multiple empty lines' no-multiple-empty-lines': ['error', {Max: 1}], semi: ['error', 'never'], // disallow trailing semicolons, quotes: ['error', 'single'], // Enforces single quotes 'space-infix-ops': 2, // must be surrounded by Spaces 'spaced-comment': ['error', 'always'], // Comments must be followed by at least one blank 'object-curly-spacing': 0, 'no-unused-expressions': 0}} duplicate codeCopy the code
Create one in the root directory.eslintignore
File, the directory or file that esLint checks to ignore
/dist/ /node_modules/ copies the codeCopy the code
inpackage.json
In thescripts
Add the following script commands to the configuration
"Lint" : eslint - ext. Vue. Js. "/", "lint: fix" : "eslint - fix - ext vue, the js. /" duplicate codeCopy the code
Introduction of Prettier uniform code style
Install Prettier and the related ESLint plug-in
NPM install prettier eslint-config-prettier eslint-plugin-prettier -d Copy codeCopy the code
Create one in the root directory.prettierrc.js
File that defines pertTier rules
Exports = {// preitterrc.js module.exports = {// the number of characters in a line is exceeded, default is 80 printWidth: 80, // a TAB represents several Spaces, default is 80 tabWidth: UseTabs: false, // Whether to use single quotation marks (default: false) singleQuote: True, / / line whether to use a semicolon, the default is true semi: false, the tail / / whether or not to use commas, there are three optional value "< none | es5 | all >" trailingComma: {foo: bar} bracketSpacing: true, // Code's parsing engine, default to Babylon, same as Babel // "parser": "Babylon ", // enables ESLint to support eslintIntegration: true} to copy codeCopy the code
Modify esLint (.eslintrc.js) configuration
1, in extends configuration value increases the plugin: prettier/it
2, add ‘prettier/prettier’ to rules: ‘error’
The modified.eslintrc.js file is as follows:
// .eslintrc.js module.exports = { root: true, parserOptions: { parser: 'babel-eslint', sourceType: 'module' }, env: { browser: true, node: true, es6: true }, extends: [ 'plugin:vue/vue3-essential', 'eslint:recommended', 'plugin:prettier/recommended' ], // add your custom rules here rules: {// "off" or 0 - off rule // "warn" or 1 - use rule as a warning // "error" or 2 - Use rule as an error 'prettier/prettier': 'error', // allow async-await 'generator-star-spacing': 'off', // 'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off', // allow debugger during development // 'no-debugger': Process.env.node_env === 'production'? 'error' : 'off', /** * best practice */ eqeqeq: 2, // Enforce === and! == 'default-case': 1, // Require switch statement with default branch 'no-else return': 1, // Disallow else block 'no-empty-function': 1, // disallow empty function' no-multi-spaces': 1, // disallow multiple Spaces radix: 1, // enforce cardinality arguments in parseInt() /** * variable declarations */ 'init-declarations': /** * ECMAScript6 */ 'arrow-spacing': ['error', {before: true, after: True}], // enforces the arrow function to use a space before and after the arrow 'no-var': 2, // disallows the var declaration variable 'object-type ': 2, // Require the object method name and attribute name to be short 'prefer-arrow-callback': 2, // require the callback function to use the arrow function 'prefer-const': // use const to declare variables that will not be modified after being declared 'prefer-rest-params': /** * style guide */ 'space-before-function-paren': 0, // Function names or function keywords must be spaced 'array-brack-spacing ': 0, // Comma-dangle ': 2 must be spaced within array brackets, // disallow trailing comma 'eol-last': {beforeColon: false, afterColon: }], // spacing must be 'keyword-spacing': ['error', {before: true, after: True}], // disallow multiple empty lines' no-multiple-empty-lines': ['error', {Max: 1}], semi: ['error', 'never'], // disallow trailing semicolons, quotes: ['error', 'single'], // Enforces single quotes 'space-infix-ops': 2, // must be surrounded by Spaces 'spaced-comment': ['error', 'always'], // Comments must be followed by at least one blank 'object-curly-spacing': 0, 'no-unused-expressions': 0}} duplicate codeCopy the code
Add the VScode configuration filesettings.json
Save automatic formatting
Note: Many plugins installed locally may cause various conflicts with ESLint, which need to be resolved as appropriate.
Create a new settings.json file in the.vscode directory under the root directory
AutoFixOnSave ": true, "editor.codeActionsOnSave": {" source.fixall.eslint ": {" source.fixall.eslint ": {" source.fixall.eslint ": {" source.fixall.eslint ": {" source.fixall.eslint ": {" source.fixall.eslint ": True}, // Save the automatically formatted "editor.formatOnSave": true} copy codeCopy the code
Add git hooks to check code ESLint before committing
Git hook management with Husky
- add
pre-commit
The hook performs esLint checking- add
commit-msg
The hook performs verification of the submission code information
Install the husky
NPM install husky -d copies the codeCopy the code
inpackage.json
In thescripts
Add the following script commands to the configuration
"Prepare ": "husky install" copies the codeCopy the code
performhusky install
Command is automatically added.husky
directory
addpre-commit
The hook,.husky
Creating a Directorypre-commit
file
Write to file
#! /bin/sh. "$(dirname "$0")/_/husky.sh" NPM run lint:fix copies codeCopy the code
addcommit-msg
The hook,.husky
Creating a Directorycommit-msg
file
#! "$(dirname "$0")/_/husky.sh" NPX --no-install commitlint --edit $1 Copy codeCopy the code
The installationcommitlint
Verify the submission information format
NPM install @commitlint/cli @commitlint/config-conventional -d Copy the codeCopy the code
Create one in the root directorycommitlint.config.js
File that defines the submission information format
/** * feature: new feature * update * fixbug * refactor: factor * optimize: Optimization of build tools or runtime performance * style: Style changes only * docs: Documents added/modified * chore: Build process or helper changes */ module.exports = {extends: [// commitlint/config-conventional']Copy the code
The introduction of vue – the router
Install the vue – the router
NPM install vue-router-s copies the codeCopy the code
newrouter
Directory, Newindex.js
file
// index.js import { createRouter, CreateWebHashHistory} from 'vue-router' import App from '@/ app. vue' // const routes = [{path: '/', Component: App, children: [ { path: '', redirect: '/home' }, { path: '/home', name: 'home', component: () => import('@/views/Home.vue') }, { path: '/login', name: 'login', component: () = > import (' @ / views/Login. Vue ')}, {/ / the change of the vue - the router @ 4, give up / / * wildcard official documents: https://next.router.vuejs.org/zh/guide/migration/index.html#%E5%88%A0%E9%99%A4%E4%BA%86-%EF%BC%88%E6%98%9F%E6%A0%87%E6%8 8%96%E9%80%9A%E9%85%8D%E7%AC%A6%EF%BC%89%E8%B7%AF%E7%94%B1 path: '/:pathMatch(.*)*', name: '404', component: () => import('@/views/404.vue')}]}] const router = createRouter({// vueRouter@3 Hash mode createWebHashHistory, history mode createWebHistory: CreateWebHashHistory (), routes}) export default Router Replicates the codeCopy the code
inmain.js
The introduction of the router
Import router from '@/router' const app = createApp(app) // route app.use(router) copy codeCopy the code
The introduction of axios
Install axios
NPM install axios -s copies the codeCopy the code
inutils/http
New directoryindex.js
import axios from 'axios' const service = axios.create({ // baseURL: '', timeout: // Request with cookie withCredentials: True}) / / request / / service. The interceptor interceptors. Request. Use (config = > {/ /}. Err = > {/ /}) / / response / / service. The interceptor interceptors. Response. Use (res = > {/ /}, err = > {/ /}) export default service copy codeCopy the code
The introduction of vuex
Install vuex
NPM install vuex-s duplicates the codeCopy the code
instore
New directoryindex.js
import { createStore } from 'vuex' const store = createStore({ state() { return { token: ''}}}) export Default Store copy codeCopy the code
inmain.js
The introduction of vuex
Import store from '@/store' const app = createApp(app) // veux app.use(store) copy codeCopy the code
Introducing the vant – the UI
Install vant
NPM I vant@next -s copy the codeCopy the code
The installationvite-plugin-style-import
Implement load on demand
NPM I vite-plugin-style-import -d copy codeCopy the code
invite.config.js
theplugins
Add the following configuration to the configuration
StyleImport ({libs: [{libraryName: 'vant', esModule: true, resolveStyle: name => 'vant /es/${name}/style '}]}) copies the codeCopy the code
Introduce vant REM adaptation scheme
Details can be viewed.The official documentationRem adaptation scheme in
Install amFE-Flexible to dynamically calculate HTML font-szie
NPM I AMFE-flexible-s Copy codeCopy the code
Install postcss – pxtorem
NPM I postcss-pxtorem -d copies the codeCopy the code
invite.config.js
To add the following configuration
PostCSS is integrated with Vite. You do not need to install it again. PostCSS: {PostCSS: {plugins: [postCssPxToRem({rootValue: 37.5, propList: ['*'],})]}}Copy the code
The introduction of less
Install less and less-Laoder
npm i less less-laoder -D
Copy the code