Vue3 + TS + Vite + elementPlus

preface

This article is further optimized based on @MK boss template vite-vue3-template. When encountering other pits during the actual development of the project, basically all pits that need to be stepped on during the actual development should be recorded and shared with everyone. Download this template to start your project directly, very useful!

  • Out of the box template download address: gitee.com/jokerchen54…

Vuex encapsulation

  • The current template has vuex modular, TS encapsulation, writing vuex will have a friendly code prompt. Although VUe3 provides a simpler way to provide and inject global state management, it does not need to write tedious getters and actions. But with vuex wrapped in this template, trust me you won’t hate Vuex anymore.

Element – plus integration

Refer to the example on the official website for an on-demand load

Unplugin-vue-components' NPM install unplugin-vue-components -d '- then add the following code to the vite configuration fileCopy the code
// vite.config.ts
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

export default {
  plugins: [
    // ...
    Components({
      resolvers: [ElementPlusResolver()],
    }),
  ],
}
Copy the code
// main.ts
import { createApp } from 'vue';
import { ElImage } from 'element-plus';
import App from './App.vue';
import router from './router/index';
import 'vue-global-api';
import store from './store';
import 'element-plus/dist/index.css';

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

Use of Chinese package

// App.vue
<script setup lang="ts">
import { ElConfigProvider } from 'element-plus';

import zhCn from 'element-plus/lib/locale/lang/zh-cn';

const locale = ref(zhCn);
</script>

<template>
  <el-config-provider :locale="locale">
    <router-view />
  </el-config-provider>
</template>
Copy the code

Vite configuration

@alias definition and usage

  • For alias definitions, first define variables in viet.config. js and configure paths in tsconfig.json
\\ vite.config.js
resolve: {
      alias: {
        The '@': resolve(__dirname, 'src'), // Set '@' to point to 'SRC'
        '@comp': resolve(__dirname, 'src/components'),}}Copy the code
\\ tsconfig.json
compilerOptions: {
    "paths": {"@": ["./src"]."@ / *": ["./src/*"]."@comp/*": ["./src/components/*"].}}Copy the code

Environment variables are defined and used

  • Start by creating the environment file in the project root directory
  • Note that the variable prefix must be VITE_APP_

# .env.development
VITE_APP_BASE_PATH = /  
Copy the code
  • Use environment variables in the.vue.ts file
console.log('environment variable BASE_PATHThe ${import.meta.env.VITE_APP_BASE_PATH}`);
Copy the code
  • Use environment variables in the viet.config.js file
import {
  loadEnv, ConfigEnv, UserConfigExport,
} from 'vite';
import vue from '@vitejs/plugin-vue';
import { resolve } from 'path';
import Components from 'unplugin-vue-components/vite';
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';

const envResolve = (mode: string, env: string) = > loadEnv(mode, process.cwd())[env];
export default ({ command, mode }: ConfigEnv): UserConfigExport= > {
  console.log('🚀 ~ process.env.node_env ~ packing path: ', envResolve(mode, 'VITE_APP_BASE_PATH'));
  return {
    plugins: [
      vue(),
      Components({
        resolvers: [ElementPlusResolver()],
      }),
    ],
  };
};

Copy the code

Dynamic loading of local images

  • Since Vite does away with require, we need to use new URL() to do an introduction.
\\ Encapsulates an import image methodfunction getImageUrl(name) { 
return new URL(`.. /assets/blogPhotos/${name}.jpg`.import.meta.url).href;
}
Copy the code
\\ App.vue
<img :src="" alt="getImageUrl(name)" />
Copy the code

Svg-icon Generic component

  • To make it easier to use SVG ICONS, encapsulate an SVG-Icon component. Vite – plugin-SVG – ICONS
  • First install the plug-in

Yarn add viet-plugin-svg - ICONS -d or NPM I viet-plugin-svg - ICONS -d

  • Configuration vite. Config. Js
import viteSvgIcons from 'vite-plugin-svg-icons';
import path from 'path'; NPM i@types /node -d
export default() = > {return {
    plugins: [
      viteSvgIcons({
        // Configure SVG to store files in your SRC
        iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')].symbolId: 'icon-[dir]-[name]',})]}; };Copy the code
  • Icon file directory/SRC /assets/ ICONS
# src/assets/icons 

icon1.svg 
icon2.svg 
icon3.svg
dir/icon1.svg
Copy the code
  • Define the SVG-Icon component
<template>
  <svg :class="svgClass" aria-hidden="true">
    <use :xlink:href="iconName" :fill="color" />
  </svg>
</template>
<script lang="ts">
import { computed, defineComponent } from 'vue';
export default defineComponent({
  props: {
    iconClass: {
      type: String.required: true,},className: {
      type: String.default: ' ',},color: {
      type: String.default: '#889aa4',}},setup(props) {
    return {
      iconName: computed(() = > `#icon-${props.iconClass}`),
      svgClass: computed(() = > {
        if (props.className) {
          return `svg-icon ${props.className}`;
        }
        return 'svg-icon'; })}; }});</script>
<style scope>
.svg-icon {
  width: 1em;
  height: 1em;
  fill: currentColor;
  vertical-align: middle;
}
</style>
Copy the code
  • Globally register common components
// main.ts
// SVG - ICONS are generic components
import 'vite-plugin-svg-icons/register';
import svgIcon from './components/common/SvgIcon/index.vue';

app.component('svg-icon', svgIcon)
Copy the code
  • How components are used
<div>
  <svg-icon icon-class="icon1" />
</div>
Copy the code

CSS preprocessing module

  • This module uses less preprocessing, using global variable configuration, configuration can be used in the. Vue file global variables
// vite.config.js
export default {
css: {
      preprocessorOptions: {
        less: {
          modifyVars: {
            hack: `true; @import (reference) "${resolve('src/assets/style/config.less')}"; `,},javascriptEnabled: true,}}},}Copy the code

Script Setup syntax sugar

Props,emit in the script setup syntax candy

<script setup lang="ts">
import { defineProps, defineEmits } from 'vue';

const props = defineProps({
  isShow: Boolean.foo: String});const emits = defineEmits(['update:foo'.'updateShow']);
const changeHandle = () = > {
  emits('update:foo'.'dd');
};
const changeIsShow = () = > {
  emits('updateShow', !props.isShow);
};
</script>
Copy the code

Vue-import-global plugin, global default import vUE some basic methods, do not need to manually import, collocation syntax sugar, reduce super much redundant code, directly take off!

  • Do not use script Setup syntax sugar
<script lang="ts">
import { onMounted, reactive, toRefs, computed, watch, onUnmounted } from 'vue'
const state = reactive({})
onMounted = () = >{
console.log('Here we go.')}const handle = () = >{}
return {
  ...toRefs(state),
  handle
}
</script>
Copy the code
  • NPM install vue-import-global -d Can be used directly after the import
<script setup lang="ts">
const state = reactive({})
console.log('Here we go.')
</script>
Copy the code