Introduction to the

Using the latest vue3, Vite2,typescript and other mainstream technologies to build a template for learning reference project.

contains

  • Technology stackUse:vue3.vite.typescriptAnd other cutting-edge technology development
  • ajax: Secondary packagingaxiosUnified management interface
  • The theme: Can be modified by yourselfelement-plusThe theme style
  • Internationalization: perfect internationalization program
  • Routing: Dynamic route generation scheme
  • Component: Secondary encapsulates commonly used components
  • tool: common instructions, filters,storageStorage, utility functions

The directory structure

| | - # public static resources | -- config. Js # config file | | -- the favicon. Ico # # the favicon icon | -- SRC the source | | - API # API request | | | - # modules Module | | | - types # interface definition | | | -- the abstract. Ts # base class | | | -- config. Ts # dictionary table | | | -- index. Ts # entry file | | | -- intercept. Ts # Interceptor | | - assets # variable of subject resources | | | | - # SCSS SCSS variable | | - theme # elemet themes | | - # components global common components | | - # config Global common configuration | | - global layout layout # | | - internationalization of locale # | | - plugin # tripartite plug-in | | - the router # global routing | | - store # global vuex | | - Utils # global public method | | | - directives # command | | | - storage # persistence | | | -- filters. Ts # filter | | | -- pager. Ts # publish-subscribe | | | - Tools. Ts # tool function | | - all page views # | | - App. Vue # entry page | | -- main. Ts # entry file | | - shims - vue. Which s | - static # # ts statement file Static resources | | - img # img | | - SVG # SVG. | - editorconfig # editorconfig. | - env. # dev environment variable development. | - env. | - pro # environment variable production Agent. The env. # proxy environment variable. | - eslintignore # eslintignore. | - eslintrc. Js # eslint configuration items. | - gitignore # gitignore | - Babel. Config. Js # Babel configuration items | -- index. HTML # HTML templates | -- package. Json # package. The json | -- README. # the README | -- md Tsconfig. Json # tsconfig | -- vite. Config. Ts # vite configuration fileCopy the code

API management

See the previous chapter for ts’s simple encapsulation of Axios

internationalization

It is recommended to use the vscode plugin i18n Ally to assist in development, with the following features

  • Inline translation display
  • Automatic completion
  • One-click machine translation
  • Unified management of all translation documents
  • Extract copy from code
  • Skip to the translation file
  • Supports JSON and YAML
  • Support for multiple directory workspaces
  • Support vuE-I18N, VUex-I18N, VUE-I18Next and NUXT-I18N
  • Plugin support for multiple languages (English, Simplified Chinese, traditional Chinese)
/ / Settings. Json configuration."i18n-ally.sourceLanguage": "zh-CN"."i18n-ally.displayLanguage": "zh-CN"."i18n-ally.enabledParsers": ["json"]."i18n-ally.extract.targetPickingStrategy": "file-previous".Copy the code

Global registration

  • src/plugin/index.ts
import { Directive } from 'vue';
import filters, { FilterKey } from '@/utils/filters';
import * as directives from '@/utils/directives/index';
import storage from '@/utils/storage';
import customMessage from '@/components/custom/custom-message';
// Tripartite plugin
import element from './element';
import i18n from './i18n';

// Detect whether webP is supported
const canvas = document.createElement('canvas');
if (canvas.getContext && canvas.getContext('2d')) {
    try {
        const isWebp = canvas.toDataURL('image/webp').includes('data:image/webp').toString();
        storage('localstorage').set('isWebp', isWebp);
    } catch (e) {
        console.error(e); }}const install = (app: any): void= > {
    // Mount the filter
    app.config.globalProperties.$filters = {};
    for(const key in filters) {
        app.config.globalProperties.$filters[key] = filters[key as keyof typeof FilterKey];
    }

    // Mount command
    Object.keys(directives).forEach(key= > {
        app.directive(key, (directives as { [key: string]: Directive })[key]);
    });

    / / registered element
    element.components.forEach((component) = > {
        if (component.name) app.component(component.name as string, component);
    });
    Object.values(element.plugins).forEach(plugin= > {
        app.use(plugin);
    });
    app.provide('$message', customMessage);

    / / i18n registration
    app.use(i18n);
};
Copy the code
  • main.ts
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';
import * as CustomPlugin from './plugin';
import * as CustomComponents from './components/custom';

const app = createApp(App);

// Register the global component
app.use(CustomComponents);
// Register global plug-ins/filters/directives
app.use(CustomPlugin);

app.use(router).use(store).mount('#container');
Copy the code

Project configuration item

Environment variables that are exposed on the import.meta.env object

  • .env.dev
# .env.dev
NODE_ENV=development

VITE_Version = 'v1.0.0'
VITE_BaseURL = '//dev.backendapi.aid.connext.net.cn/'
Copy the code
  • abstract.ts
console.log(import.meta.env.VITE_BaseURL) // dev.backendapi.aid.connext.net.cn/
Copy the code

vite.config.ts

import { defineConfig, loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue';
import viteCompression from 'vite-plugin-compression';
import styleImport from 'vite-plugin-style-import';
import vueI18n from '@intlify/vite-plugin-vue-i18n';
const path = require('path');
const port = 7000;
const timeStamp = Date.now();
Copy the code
  • Vite plugin used
export default ({ mode }: { mode: string }): unknown= >{ process.env = {... process.env, ... loadEnv(mode, process.cwd())};return defineConfig({
        plugins: [
            vue(),
            viteCompression({
                verbose: true.disable: false.threshold: 1024 * 10.algorithm: 'gzip'.ext: '.gz'
            }),
            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}`;
                        }
                    }
                ]
            }),
            vueI18n({
                compositionOnly: false.include: path.resolve(__dirname, './src/locale/**')]}})); };Copy the code
  • packagingchunkNaming and code splitting
export default ({ mode }: { mode: string }): unknown= >{ process.env = {... process.env, ... loadEnv(mode, process.cwd())};return defineConfig({
    build: {
      assetsDir: 'static/assets'.rollupOptions: {
        output: {
          entryFileNames: `static/js/[name].${process.env.VITE_Version}.t${timeStamp}.js`.chunkFileNames: `static/js/[name].${process.env.VITE_Version}.t${timeStamp}.js`.assetFileNames: `static/js/[name].${process.env.VITE_Version}.t${timeStamp}.[ext]`,},manualChunks(id) {
          const chunkMap = new Map(a); chunkMap.set(/[\\/]src[\\/]layout[\\/]/.test(id), 'basicLayout');
          chunkMap.set(/[\\/]src[\\/]components[\\/]/.test(id), 'basicComponent');
          chunkMap.set(/[\\/]node_modules[\\/]echarts[\\/]/.test(id), 'echarts');
          chunkMap.set(/[\\/]node_modules[\\/]lodash[\\/]/.test(id), 'lodash');
          chunkMap.set(/[\\/]node_modules[\\/]moment[\\/]/.test(id), 'moment');
          chunkMap.set(/[\\/]node_modules[\\/]qiankun[\\/]/.test(id), 'qiankun');
          chunkMap.set(/[\\/]node_modules[\\/]xlsx[\\/]xlsx.js/.test(id), 'xlsxIndex');
          chunkMap.set(/[\\/]node_modules[\\/]xlsx[\\/](? ! (xlsx.js))/.test(id), 'xlsx');
          chunkMap.set(/[\\/]node_modules[\\/]element-plus[\\/]/.test(id), 'element');
          return chunkMap.get(true) | |'vendors'; }}}}); };Copy the code

Install and use

  • Cloning project
git clone https://github.com/sunweijieMJ/vite-vue3-temp.git
Copy the code
  • Install dependencies
cdVite-vue3 - Temp YARN or NPM ICopy the code
  • run
Yarn serve dev or NPM run serve devCopy the code
  • packaging
Yarn Build Pro or NPM Run Build ProCopy the code

Attached is github project address: vite-vue3-temp, please click a star