A series of articles on Vue3+Vite+Ts+Pinia+Sass project guide for front-end newbies - Chapter 5 Installation and use of component library (Element-Plus basic configuration)

Table of contents of series of articles (click to view)



Preface

UseElement-Plus component library for development, as introduced onofficial website,Element-Plus Has the following benefits:

  • Consistency

    • Consistent with real life: consistent with the processes and logic of real life, and following the language and concepts that users are accustomed to;

    • Consistency in the interface: All elements and structures need to be consistent, such as: design style, icons and text, position of elements, etc.

  • Feedback Feedback

    • Control feedback: Allow users to clearly perceive their operations through interface style and interactive effects;

    • Page feedback: After operation, the current status is clearly displayed through changes in page elements.

  • Efficiency

    • Simplify the process: Design a simple and intuitive operation process;

    • Clear and unambiguous: The language is clearly expressed and the meaning is clear, allowing users to quickly understand and make decisions;

    • Help users identify: The interface is simple and straightforward, allowing users to quickly identify rather than recall, reducing the user's memory burden.

  • Controllability

    • User decision-making: User operation suggestions or safety tips can be given according to the scenario, but it cannot make decisions on behalf of the user;

    • Controllable results: Users can perform operations freely, including undoing, rolling back, and terminating current operations.


1. Installation

Insert image description here
Open a new terminal in the project root directory and use yarn or other tools to install dependencies.

Official website code:

# 选择一个你喜欢的包管理器

# NPM
$ npm install element-plus --save

# Yarn
$ yarn add element-plus

# pnpm
$ pnpm install element-plus

Insert image description here

2. Quick start

Change all the js files in the system to ts files in the scr directorymain.tsIn file

import {
    
     createApp } from 'vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import App from './App.vue'

const app = createApp(App)

app.use(ElementPlus)
app.mount('#app')

3. Automatic introduction

1. First you need to install the two plug-ins unplugin-vue-components and unplugin-auto-import

npm install -D unplugin-vue-components unplugin-auto-import

2. Add the following code to the vite.config.ts file

import {
    
     defineConfig } from 'vite'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import {
    
     ElementPlusResolver } from 'unplugin-vue-components/resolvers'

export default defineConfig({
    
    
  // ...
  plugins: [
    // ...
    AutoImport({
    
    
      resolvers: [ElementPlusResolver()],
    }),
    Components({
    
    
      resolvers: [ElementPlusResolver()],
    }),
  ],
})

4. Configure vite and plugins yourself

1. Installationplugins

yarn add vite-plugin-svg-icons
yarn add vite-plugin-vue-setup-extend
yarn add vite-plugin-html
yarn add vite-plugin-top-level-await

Insert image description here
Insert image description here
Insert image description here
Insert image description here

2, addition vite.plugins.ts sentence item

import path from 'path'
import vue from '@vitejs/plugin-vue'
import {
    
     createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import setupExtend from 'vite-plugin-vue-setup-extend'
import Components from 'unplugin-vue-components/vite'
import AutoImport from 'unplugin-auto-import/vite'
import {
    
     ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import {
    
     createHtmlPlugin } from 'vite-plugin-html'
import topLevelAwait from 'vite-plugin-top-level-await'

export default function createVitePlugins(viteEnv, isBuild = false) {
    
    
  const {
    
     VITE_GLOB_APP_TITLE } = viteEnv
  const vitePlugins = [
    vue(),
    setupExtend(),
    createSvgIconsPlugin({
    
    
      // 指定需要缓存的图标文件夹
      iconDirs: [path.resolve(process.cwd(), 'src/assets/icons/svg')],
      // 指定symbolId格式
      symbolId: 'icon-[dir]-[name]'
    }),
    Components({
    
    
      resolvers: [ElementPlusResolver()]
    }),
    AutoImport({
    
    
      // resolvers: [ElementPlusResolver()],
      // targets to transform
      include: [/\.[tj]sx?$/, /\.vue$/, /\.vue\?vue/, /\.md$/],
      // global imports to register
      imports: [
        // 插件预设支持导入的api
        'vue',
        'vue-router',
        'pinia'
        // 自定义导入的api
      ],

      // Generate corresponding .eslintrc-auto-import.json file.
      // eslint globals Docs - https://eslint.org/docs/user-guide/configuring/language-options#specifying-globals
      eslintrc: {
    
    
        enabled: false, // 默认false, true启用。生成一次就可以,避免每次工程启动都生成
        filepath: './.eslintrc-auto-import.json', // Default `./.eslintrc-auto-import.json`
        globalsPropValue: true // Default `true`, (true | false | 'readonly' | 'readable' | 'writable' | 'writeable')
      },

      // Filepath to generate corresponding .d.ts file.
      // Defaults to './auto-imports.d.ts' when `typescript` is installed locally.
      // Set `false` to disable.
      dts: './auto-imports.d.ts',

    }),
    createHtmlPlugin({
    
    
      minify: isBuild,
      inject: {
    
    
        data: {
    
    
          title: VITE_GLOB_APP_TITLE
        }
      }
    }),
    topLevelAwait({
    
    
      // The export name of top-level await promise for each chunk module
      promiseExportName: '__tla',
      // The function to generate import names of top-level await promise in each chunk module
      promiseImportName: i => `__tla_${
     
     i}`
    })
  ]
  return vitePlugins
};

3, revised vite.config.ts text

import path from 'path'
import {
    
     defineConfig, loadEnv } from 'vite'
import createVitePlugins from './vite.plugins'

const base_url = 'xxx'

// https://vitejs.dev/config/
export default defineConfig(({ mode, command }) => {
  const env = loadEnv(mode, process.cwd())
  return {
    
    
    plugins: createVitePlugins(env, command === 'build'),
    base: './',

    resolve: {
    
    
      alias: {
    
    
        '@': path.resolve(__dirname, 'src')
      },
      extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue']
    },
    server: {
    
    
      host: "0.0.0.0",
      proxy: {
    
    
        '/xxx': {
    
    
          target: base_url,
          changeOrigin: true,
        }
      }
    }
  }
})

5. Test components

1. Delete useless files

Before testing whether the component is available, delete some useless files to ensure that our directory files are pure.

  • Exclusion src/components/HHelloWorld.vue Sentence
  • Delete App.vue Replace the file content with the following
<template>
  <div>

  </div>
</template>

<script setup lang="ts">

</script>

<style scoped></style>

2. Test whether it is available

In App.vue, enter the component library code and check the page to see if it is successful.

<template>
  <div>
    <el-row class="mb-4">
      <el-button>Default</el-button>
      <el-button type="primary">Primary</el-button>
      <el-button type="success">Success</el-button>
      <el-button type="info">Info</el-button>
      <el-button type="warning">Warning</el-button>
      <el-button type="danger">Danger</el-button>
    </el-row>
  </div>
</template>

<script setup lang="ts">

</script>

<style scoped></style>

Insert image description here


Summarize

In this article, the installation and quick start process for developing using the Element-Plus component library are introduced. The article first introduces the advantages of Element-Plus component libraries, including consistency, feedback, efficiency and controllability. It then details the steps to install Element-Plus, as well as a quick start guide in code. Subsequently, the automatic introduction and custom configuration Vite and plug-ins were explained in detail. Finally, before testing the component availability, some files were deleted to ensure the purity of the project, and the use of the component library was demonstrated through sample code. The configuration code above can be found in the github warehouse Directlycopy, warehouse path:https://github.com/SmallTeddy/music-explorer-web.

Guess you like

Origin blog.csdn.net/SmallTeddy/article/details/134507363