• The online preview

  • Code warehouse

  • The TypeScript version

Introduction (Introduction to Vite)

Vite is a development and construction tool. In the development process, it uses the browser native ES Module feature to import organizational code, and uses rollup as a packaging tool in production. It has the following features:

  • The speed of light to start
  • Hot Module Replacement
  • According to the need to compile

For more information, click on the Vite portal

Start (project setup)

Please ensure that node.js is successfully installed on your computer. This project uses the Vite build tool and requires node.js version >= 12.0.0.

View the node.js version:

node -v
Copy the code

Use Vite to quickly initialize the project

Use NPM:

npm init @vitejs/app
Copy the code

Using Yarn:

yarn create @vitejs/app
Copy the code

Then complete the following operations as prompted:

  1. Enter the project name

For example, the project name is vue3-element-admin

  1. Select a template

When we select VUE, Vue3 is automatically installed

You can also directly specify the project name and the template you want to use through additional command-line options. For example, to build a Vite + Vue project, run:

# 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

Supported template presets include:

  • vanilla
  • vue
  • react
  • preact
  • lit-element
  • svelte
  1. Install dependencies
cd ./vue3-element-admin
npm install
Copy the code
  1. Start the project
npm run dev
Copy the code

As shown in the figure above, the simple skeleton of Vite + Vue3 project has been built. Now let’s integrate Vue Router, Vuex, Element Plus and Sass for this project.

Modify the Vite configuration file

The Vite configuration file vite.config.js is located in the root directory and is automatically read when the project is started.

This project first do some simple configuration, such as: set @ to SRC directory, service start port, packaging path, proxy, etc.

import { defineConfig } from 'vite'
import { resolve } from 'path'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig(({ command }) = > {
  return {
    base: '/'.// Common base path for development or production environment services.
    plugins: [vue()],
    resolve: {
      alias: {
        The '@': resolve('./src'), // Set '@' to point to 'SRC'
        '@img': resolve('./src/assets/img'),}},server: {
      port: 7001.// Set the service startup port number
      open: false.// Set whether the browser opens automatically when the service starts
      // Set the proxy based on the actual situation of the project
      proxy: {
        '/api': 'http://admin.xueyueob.cn/api',},},}})Copy the code

The directory structure

├─ publish/ ├─ SRC / ├─ Assets // / ├─ Components // // // // // // // // // // // // // // // // // // │ ├─ styles │ ├─ utils │ ├─ views │ ├─ app.vue │ ─ main.js │.html │ ├─ styles │ ├─ utils │ ├─ API.vue │ ─ main.js │.html ├ ─ ─ vite. Config. Js / / vite configuration file └ ─ ─ package. The jsonCopy the code

Integrated routing management tool Vue Router

  1. Install Vue3 supported routing tool vue-router@next
npm i vue-router@next
Copy the code
  1. createsrc/router/index.jsfile

Create router directory SRC and create index.js file in router directory:

└─ SRC / ├─ router/ ├─ index.js //Copy the code
import { createRouter, createWebHistory } from 'vue-router'

export const constantRoutes = [
  {
    path: '/login'.component: () = > import('@/views/login/index.vue'),
    name: 'Login'.meta: {
      title: 'login',}}, {path: '/'.component: () = > import('@/layout/index.vue'),
    redirect: '/dashboard'.children: [{path: '/dashboard'.component: () = > import('@/views/dashboard/index.vue'),
        name: 'Dashboard'.meta: { title: 'home'.icon: 'el-icon-s-home'.affix: true}, {},path: '/user'.component: () = > import('@/views/user/user.vue'),
        name: 'User'.meta: { title: 'users'.icon: 'el-icon-user-solid'.roles: ['admin'.'editor']},},],]export const router = createRouter({
  history: createWebHistory(),
  routes: constantRoutes,
})

export default router
Copy the code

Depending on the routing configuration of this project, you will need to create a view directory under SRC to store page components.

Code Demo portal can be copied directly

  1. Mount the routing configuration in the main.js file
import { createApp } from 'vue'
import App from './App.vue'
import router from './router/index'

createApp(App).use(router).mount('#app')
Copy the code

Vuex integrated status management tool

  1. Install Vue3 supported status management tool vuex@next
npm i vuex@next
Copy the code
  1. createsrc/store/index.jsfile

Create a store directory under SRC and create an index.js file in store:

└ ─ ─ SRC / ├ ─ ─ store / ├ ─ ─ modules / ├ ─ ─ app. Js ├ ─ ─ tagsView. Js ├ ─ ─ index. The js / / store the configuration fileCopy the code

Here I use the import.meta.globEager function to import all modules in the modules directory :(automatic, once and for all)

// indes.js
import { createStore } from 'vuex'

const modulesFiles = import.meta.globEager('./modules/*.js')
const pathList = []

for (const path in modulesFiles) {
  pathList.push(path)
}

const modules = pathList.reduce((modules, modulePath) = > {
  const moduleName = modulePath.replace(/^\.\/modules\/(.*)\.\w+$/.'$1')
  const value = modulesFiles[modulePath]
  modules[moduleName] = value.default
  return modules
}, {})

const store = createStore({
  modules,
})

export default store
Copy the code
// app.js
const state = {
  device: 'desktop',}const mutations = {
  TOGGLE_DEVICE: (state, device) = > {
    state.device = device
  },
}

const actions = {
  toggleDevice({ commit }, device) {
    commit('TOGGLE_DEVICE', device)
  },
}

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

use

// app tagsView is the module in modules
this.$store.dispatch('app/toggleDevice'.'mobile')
this.$store.dispatch('tagsView/addVisitedView'.'user')
Copy the code
  1. inmain.jsThe Vuex configuration is mounted to the file
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

createApp(App).use(router).use(store).mount('#app')
Copy the code

Integrated UI framework Element Plus

  1. Install Element Plus, a UI framework that supports Vue3
npm i element-plus
Copy the code
  1. Mount Element Plus in main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

import ElementPlus from 'element-plus'
import 'element-plus/lib/theme-chalk/index.css'

createApp(App).use(router).use(store).use(ElementPlus).mount('#app')
Copy the code

Integrated CSS precompiler Sass

  1. The installationsass
npm i sass -D
Copy the code
  1. use
<style lang="scss">.</style>
Copy the code

At this point, a front-end project development environment based on Vite + Vue3 + Vue Router + Vuex + Element Plus + Sass has been built, and the project Demo is hosted in GitHub warehouse. If you need it, you can download it for reference.

End (Q&A)

Our title is to build a set of background management system project. Not reflected? The title party? Hold on. Let’s keep going ^-^

Let’s download a vue- Element-Admin background management system template of 67.2K Star developed and maintained by @Panjiachen. Then we copy the SRC directory to replace our SRC directory, make a backup before replacing it, and replace the router store main.js from above. Run the project

You’ll find a lot of errors, which is normal. Because vue3 has some major changes from VUe2; There are also minor changes to element-UI and Element-Plus; Therefore, the process of solving the error is the process of vue2 upgrading vue3. Due to the length of the report, the process of resolving the error is not listed. If you are interested, you can go to the vUE official website to check the changes to the VUE official website portal

And for those of you who like TypeScript, I’ve written a version of TypeScript. Downstairs take ^_^

  • The JavaScript version

  • The TypeScript version

Postscript (ES6 series)

With modern browsers supporting ES6, we can write simpler and more elegant code with ES6. In my next article, I’ll list a number of best practices for using ES6!