preface

Start the 2021 learning journey, mainly introduce the actual combat process of learning vitE2 and VUE3. Building Vite2 + Vue3+Element-Plus + Vue-Router4 + Vuex + Eslint from scratch

Introduce vite

Vite (French for "fast", pronounced /vit/) is a new front end build tool. Consists of an out-of-the-box development server plus a set of build directives. Vite takes advantage of the browser's native ES module support and esBuild-based dependency pre-packaging to significantly improve the front-end development experience.Copy the code

Initialize the project

# NPM 6.x NPM init@vitejs /app my-vue-app --template vue # NPM 7+  npm init @vitejs/app my-vue-app -- --template vue # yarn yarn create @vitejs/app my-vue-app --template vueCopy the code

The alias set

Modify the vite. Config. Js

import path from 'path' export default defineConfig({ ... , resolve: { alias: { '@': path.resolve(__dirname, 'src'), components: path.resolve(__dirname, 'src/components'), assets: path.resolve(__dirname, 'src/assets'), views: path.resolve(__dirname, 'src/views'), utils: path.resolve(__dirname, 'src/utils'), apis: path.resolve(__dirname, 'src/apis'), }, } })Copy the code

SCSS pretreatment

SCSS is a CSS preprocessing language that is an updated version of SASS. SCSS is a new version of SASS 3, which is fully compatible with CSS3 and inherits the power of SASS.

Install the sass

  npm i -d sass node-sass sass-loader
Copy the code

Introduce the SASS global variable/style

# vite.config.js export default defineConfig({ ... , css: { preprocessorOptions: { scss: {/ / @ / SRC/alias / / so it is assumed that you have a ` SRC/assets/SCSS/variables. The SCSS ` additionalData this file: `@import "@/assets/scss/variables.scss"; '},},}})Copy the code

ElementUI

Start introducing the UI framework, here using Element to fit vuE3 version of Element-Plus

The installation element

  npm i -s element-plus
Copy the code

Load components on demand

With the help of ite-plugin-style-import to load components on demand, in order to reduce the size of the project

The installation
vite-plugin-style-import \textrm\color{red}{vite-plugin-style-import}

npm install vite-plugin-style-import -D
Copy the code

Modify the
vite.config.js \textrm\color{red}{vite.config.js}

import styleImport from 'vite-plugin-style-import'
plugins: [
  vue(),
  styleImport({
    libs: [
      {
        libraryName: 'element-plus',
        esModule: true,
        ensureStyleFile: true,
        resolveStyle: (name) => {
          name = name.slice(3);
          return `element-plus/packages/theme-chalk/src/${name}.scss`;
        },
        resolveComponent: (name) => {
          return `element-plus/lib/${name}`;
        },
      },
    ],
  })
]
Copy the code

Create a new element

// If you want to use.scss style files, SCSS file // import 'element-plus/packages/theme-chalk/ SRC /base.scss' import 'element-plus/packages/theme-chalk/src/base.scss' import { ElAlert, ElAside, ElAutocomplete, ElAvatar, ElBacktop, ElBadge, ElBreadcrumb, ElBreadcrumbItem, ElButton, ElButtonGroup, ElCalendar, ElCard, ElCarousel, ElCarouselItem, ElCascader, ElCascaderPanel, ElCheckbox, ElCheckboxButton, ElCheckboxGroup, ElCol, ElCollapse, ElCollapseItem, ElCollapseTransition, ElColorPicker, ElContainer, ElDatePicker, ElDialog, ElDivider, ElDrawer, ElDropdown, ElDropdownItem, ElDropdownMenu, ElFooter, ElForm, ElFormItem, ElHeader, ElIcon, ElImage, ElInput, ElInputNumber, ElLink, ElMain, ElMenu, ElMenuItem, ElMenuItemGroup, ElOption, ElOptionGroup, ElPageHeader, ElPagination, ElPopconfirm, ElPopover, ElPopper, ElProgress, ElRadio, ElRadioButton, ElRadioGroup, ElRate, ElRow, ElScrollbar, ElSelect, ElSlider, ElStep, ElSteps, ElSubmenu, ElSwitch, ElTabPane, ElTable, ElTableColumn, ElTabs, ElTag, ElTimePicker, ElTimeSelect, ElTimeline, ElTimelineItem, ElTooltip, ElTransfer, ElTree, ElUpload, ElInfiniteScroll, ElLoading, ElMessage, ElMessageBox, ElNotification, } from 'element-plus'; const components = [ ElAlert, ElAside, ElAutocomplete, ElAvatar, ElBacktop, ElBadge, ElBreadcrumb, ElBreadcrumbItem, ElButton, ElButtonGroup, ElCalendar, ElCard, ElCarousel, ElCarouselItem, ElCascader, ElCascaderPanel, ElCheckbox, ElCheckboxButton, ElCheckboxGroup, ElCol, ElCollapse, ElCollapseItem, ElCollapseTransition, ElColorPicker, ElContainer, ElDatePicker, ElDialog, ElDivider, ElDrawer, ElDropdown, ElDropdownItem, ElDropdownMenu, ElFooter, ElForm, ElFormItem, ElHeader, ElIcon, ElImage, ElInput, ElInputNumber, ElLink, ElMain, ElMenu, ElMenuItem, ElMenuItemGroup, ElOption, ElOptionGroup, ElPageHeader, ElPagination, ElPopconfirm, ElPopover, ElPopper, ElProgress, ElRadio, ElRadioButton, ElRadioGroup, ElRate, ElRow, ElScrollbar, ElSelect, ElSlider, ElStep, ElSteps, ElSubmenu, ElSwitch, ElTabPane, ElTable, ElTableColumn, ElTabs, ElTag, ElTimePicker, ElTimeSelect, ElTimeline, ElTimelineItem, ElTooltip, ElTransfer, ElTree, ElUpload, ]; const plugins = [ ElInfiniteScroll, ElLoading, ElMessage, ElMessageBox, ElNotification, ]; const option = { size: 'small', zIndex: = > {3000} export default (app)/element/global configuration app. Config. GlobalProperties. $element = option components.forEach((component) => { app.component(component.name, component); }); plugins.forEach((plugin) => { app.use(plugin); }); };Copy the code

Modify the main js

import useElement from '@/utils/element.js';
const app = createApp(App)
useElement(app)
app.mount('#app')
Copy the code

Matters needing attention

Error: @use rules must be written before any other rules. `@import "assets/scss/variables.scss"; ` + additionalData: `@use "assets/scss/variables.scss" as *; `Copy the code

vue-router

Vue Router is the route manager of Vue. It is deeply integrated with the core of Vue.js and is one of the core plug-ins of Vue.

Install the vue – the router

NPM I - s [email protected]Copy the code

Create a router directory and file

Creating a Router Directory

Create a router directory folder under the SRC directory

A new index. Js

Create index.js in the router directory

Import {createRouter, createWebHistory} from "vue-router"; Import Layout from '@/ Layout '/ ** * Define route array */ const routes = [{// 404 route name: '404, path: '/404', component: () = > import (' / @ / views/error / 404. Vue ')}, {/ / 401 routing name: '401', path: '/ 401', component: () => import('@/views/error/401.vue'), hidden: true }, { name: 'home', path: "/home", component: () => import("/@/views/home/home.vue"), } ]; /** * create route */ const router = createRouter({// hash mode: createWebHashHistory, // History mode: createWebHistory history: createWebHistory("/"), // history:createWebHashHistory(), routes, }); /** * Route Guard */ route.beforeeach ((guard) => {beforeEach. CheckAuth (guard, router); }); /** * Route error callback */ router.onError((handler) => {console.log("error:", handler); }); /** * Output object */ export default RouterCopy the code

Modify the main js

import { createApp } from 'vue'
import App from './App.vue'
import useElement from '@/utils/element.js';
import router from '@/router/index.js'

const app = createApp(App)
useElement(app)
app.use(router)
app.mount('#app')

Copy the code

vuex

Install vuex

npm i vuex@4 -s
Copy the code

Create a store directory and file

Creating a Store Directory

Create a store directory under the SRC directory

Create the index.js file

Create the index.js file in the store directory

import { createStore, Store } from 'vuex';
import user from './modules/user';
import getters from './getters'

const store = createStore({
  modules: { user },
  getters
});

export default store

Copy the code

Create modules and Module files

// src/store/modules/user.js
const state = {
  name: 'hello vue3',
  age: 18
}

const mutations = {
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AGE: (state, age) => {
    state.age = age
  }
}

const actions = {
  setName({ commit }, name) {
    commit('SET_NAME', name)
  },
  setAge({ commit }, age) {
    commit('SET_AGE', age)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
Copy the code

Modify the main js

import { createApp } from 'vue'
import App from './App.vue'
import useElement from '@/utils/element.js';
import router from '@/router/index.js'
import i18n from '@/i18n/index.js'
import store from '@/store/index.js' //++++

const app = createApp(App)
app.use(router)
app.use(store)                       //++++
app.use(i18n)
useElement(app)
app.mount('#app')

Copy the code

internationalization

Internationalization is achieved through vue-I18N

Install the vue – i18n

npm i vue-i18n@next -s
Copy the code

The i18N configuration file was added

Create the i18n directory in the SRC directory and create the cn.js and en.js multi-language configuration files

// SRC /i18n/cn.js export default {message: {hello: 'Vue3'}}; // src/i18n/en.js export default { message: { hello: 'Hello Vue3' } };Copy the code

Added the i18N entry file

Create index.js in the i18n directory

// src/i18n/index.js import { createI18n } from 'vue-i18n'; import cn from './cn.js'; import en from './en.js'; const messages = { en: { ... en }, 'zh-cn': { ... cn } } const i18n = createI18n({ locale: localStorage.getItem('lang') || 'zh-cn', messages }); export default i18n;Copy the code

Modify the main js

import { createApp } from 'vue'
import App from './App.vue'
import useElement from '@/utils/element.js';
import router from '@/router/index.js'
import i18n from '@/i18n/index.js'

const app = createApp(App)
app.use(router)
app.use(i18n)
useElement(app)
app.mount('#app')
Copy the code

ESLint

Code specification is important when coding. ESLint can avoid many coding errors and improve code readability. Airbnb JavaScript code specification is used here.

Install eslint

npm i -d eslint eslint-config-airbnb-base eslint-plugin-import eslint-plugin-vue
Copy the code

Added the.eslintrc.js configuration file

/ / module. Exports = {extends: ['plugin:vue/vue3-essential', 'airbnb-base'], parserOptions: { sourceType: 'module', ecmaVersion: 2020, }, plugins: ['vue'], rules: { ... }};Copy the code

Configure the. Eslintignore file

# configure ESLint to ignore files and create an.eslintignore file in the root directory, adding configurations as required, such as /node_modules /distCopy the code

conclusion

Toss a day or two, basically according to the official website guide to operate, according to the steps to complete the construction.

The forward portal

Architecture design based on Vue

Nodejs version management

Vscode development tool optimization