PK creative Spring Festival, I am participating in the “Spring Festival creative submission contest”, please see: Spring Festival creative submission Contest

preface

The coming New Year is destined to be the year of the rise of Vue3 and the year of accelerated construction represented by Vite. In my previous post, which Front-end Technologies will Be Hot in 2022? As mentioned, we have been using the VUE3 framework since 2020 and have developed several commercial-grade projects to prove the stability of the framework.

Recently, UVU announced that Vue3 has become the default version, which means that Vue3 will become the main direction of community maintenance. In order to let more friends enter VuE3 quickly, I launched an open source template on Githubfast-vue3In order to provide scaffolding out of the box, quickly through the first gear start (various configurations), directly experience the acceleration phase (actual project). The configuration itself is not that difficult, just read the documentation later.

FastVue3

Fast-vue3, is vue3 +Vite2.7+TypeScript+Pinia and other Vue development tool chain. Sorted out the current more mainstream tool chain, can be used directly out of the box, convenient for small partners to learn, the best way to learn – while learning while learning

Not a wheel, a template tool

The characteristics of

  • πŸ’• fast-vue3, the framework base supports vue3 +Vite2.7+TypeScript+Pinia.

  • πŸ”Œ supports Husky and Lint-staged code specification collaboration for large factory teams

  • πŸ–ΌοΈ supports SVG ICONS and has encapsulated a simple SvgIcon component that can read SVG directly from a file

  • βš™οΈ supports Plop, automatic generation of code files, provides three preset templates pages, Components, Store and so on can be customized

  • πŸ“¦ supports Axios (TS version), which encapsulates the main interceptor, request invocation, and other methods

  • πŸ‘½ supports router and Store modularization and has built-in routing hooks

  • 🐳 supports env, environment variables, and differentiated packaging environments

  • 🍑 Supports automatic introduction of unplugin-vue-components

  • πŸ— supports VW/VH mobile layout compatibility, or you can configure your own build files using PLOp

  • πŸ“± support viet-plugin-mdmarkdown rendering

  • πŸ₯˜ support viet-plugin-pages to automatically generate routes based on files

  • πŸ€– support viet-plugin-restart, listen for viet. config or env file changes and automatically restart

  • πŸŽ‰ is currently collecting more tools and adding them to….

use

Three links with one button: Star or Fork or visual warehouse

#Pull warehouse code
git clone  https://github.com/MaleWeb/fast-vue3.git

#Go to project folder
cd fast-vue3 

#Installation project dependencies
pnpm install

#run
pnpm run dev
Copy the code

If no error is reported, congratulations on your successful ignition. Otherwise, see the FAQ below.

If you already know this template, it is recommended that you pull out the Template branch for project development, which does not contain any sample code.

# clone the template branch git clone - b template at https://github.com/MaleWeb/fast-vue3.gitCopy the code

Function highlights

Here is a brief introduction to some of the core parts, the installation part will not go into detail, you are advised to read the official documentation or visual warehouse

πŸͺ‚ DACHang Collaboration – code specification

πŸͺ Most large factory teams currently use husKY and Lint-staged constraints for code specifications

  • throughpre-commitImplement Lint checking, unit testing, code formatting, and more.
  • Combine with VsCode editor (automatic formatting when saving: editor.formatonsave: true)
  • (Pre-commit => NPM run Lint: Lint-passage) Use Git hooks (pre-commit => NPM run Lint: Lint-passage)
  • IDE configuration (.editorconfig), ESLint configuration (.eslintrc.jsΒ ε’ŒΒ .eslintignore), StyleLint configuration (.stylelintrcΒ ε’ŒΒ .stylelintignore), see the corresponding configuration file for details.

πŸ”Œ close the code specification and omit SRC/to.eslintignore and.stylelintignore respectively.

πŸ’• supports JSX syntax

{..."@vitejs/plugin-vue-jsx": "^ 1.3.3." ". }Copy the code

🎸UI components are loaded on demand and automatically imported

//
import Components from 'unplugin-vue-components/vite'
export const AutoRegistryComponents = () = > {
    return Components({
        extensions: ['vue'.'md'].deep: true.dts: 'src/components.d.ts'.directoryAsNamespace: false.globalNamespaces: [].directives: true.include: [/\.vue$/./\.vue\? vue/./\.md$/].exclude: [/[\\/]node_modules[\\/]/./[\\/]\.git[\\/]/./[\\/]\.nuxt[\\/]/].resolvers: [
            IconsResolver({
                componentPrefix: ' ',
            }),
            ArcoResolver({ importStyle: 'less' }),// Add UI frames according to your needs
            VueUseComponentsResolver(),// The VueUse component is used by default],})}Copy the code

🧩Vite plug-in modularization

In order to manage plugins easily, we put all config files into config/vite/plugins. In the future, more plugins will be managed in folders. It is worth mentioning that fast-vue3 adds unified environment variable management to distinguish between dynamically opening certain plug-ins.

// vite/plugins/index.ts
/ * * *@name createVitePlugins
 * @description Encapsulate the plugins array with a unified call to */
import type { Plugin } from 'vite';
import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import { ConfigSvgIconsPlugin } from './svgIcons';
import { AutoRegistryComponents } from './component';
import { AutoImportDeps } from './autoImport';
import { ConfigMockPlugin } from './mock';
import { ConfigVisualizerConfig } from './visualizer';
import { ConfigCompressPlugin } from './compress';
import { ConfigPagesPlugin } from './pages'
import { ConfigMarkDownPlugin } from './markdown'
import { ConfigRestartPlugin } from './restart'

export function createVitePlugins(isBuild: boolean) {
    const vitePlugins: (Plugin | Plugin[])[] = [
        / / the vue support
        vue(),
        / / JSX support
        vueJsx(),
        // Automatically import components on demand
        AutoRegistryComponents(),
        // Automatically import dependencies on demand
        AutoImportDeps(),
        // Automatically generate routes
        ConfigPagesPlugin(),
        // Enable. Gz compression rollup-plugin-gzip
        ConfigCompressPlugin(),
        / / support markdown
        ConfigMarkDownPlugin(),
        // Listen for configuration file changes and restart
        ConfigRestartPlugin(),
    ];
    // vite-plugin-svg-icons
    vitePlugins.push(ConfigSvgIconsPlugin(isBuild));
    // vite-plugin-mock
    vitePlugins.push(ConfigMockPlugin(isBuild));
    // rollup-plugin-visualizer
    vitePlugins.push(ConfigVisualizerConfig());
    return vitePlugins;
}
Copy the code

Vite.config. ts is much cleaner

import { createVitePlugins } from './config/vite/plugins'.return {
    resolve: {
      alias: {
        "@": path.resolve(__dirname, './src'),
        '@config': path.resolve(__dirname, './config'),
        "@components": path.resolve(__dirname, './src/components'),
        '@utils': path.resolve(__dirname, './src/utils'),
        '@api': path.resolve(__dirname, './src/api'),}},// plugins
    plugins: createVitePlugins(isBuild)
}
...
Copy the code

πŸ“± supportPinia, the next generation ofVuex5

Create the file SRC /store/index.ts

// Supports modularization, and ploP can be generated through the command line with one key
import { createPinia } from 'pinia';
import { useAppStore } from './modules/app';
import { useUserStore } from './modules/user';
const pinia = createPinia();
export { useAppStore, useUserStore };
export default pinia;
Copy the code

Create a file SRC/store/modules/user/index. The ts

import { defineStore } from 'pinia'
import piniaStore from '@/store'
export const useUserStore = defineStore(
    / / the only ID
    'user',
    {
        state: () = > ({}),
        getters: {},
        actions: {}})Copy the code

πŸ€– supportPlopAutomatic file generation

βš™οΈ code files automatically generated, providing three preset templates pages, Components, Store, can also be designed according to their own needs more automatically generated scripts. General backend students use this form, very efficient.

#Install the plop
pnpm add plop
Copy the code

The root directory creates plopfile.ts

import { NodePlopAPI } from 'plop';
export default function (plop: NodePlopAPI) {
    plop.setWelcomeMessage('Select the schema you want to create:')
    plop.setGenerator('page'.require('./plop-tpls/page/prompt'))
    plop.setGenerator('component'.require('./plop-tpls/component/prompt'))
    plop.setGenerator('store'.require('./plop-tpls/store/prompt'))}Copy the code
#Start the command
pnpm run plop
Copy the code

πŸ–Ό ️ supportSVGicon

As browser compatibility improves and SVG performance becomes more prominent, many large factory teams are creating their own SVG management libraries, which will be recommended in the toolkit.

#Installing SVG dependencies
pnpm add vite-plugin-svg-icons
Copy the code

Configuration vite. Config. Ts

import viteSvgIcons from 'vite-plugin-svg-icons';
export default defineConfig({
plugins:[
...
 viteSvgIcons({
    // Specify the icon folder to cache
    iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')].// Specify the symbolId format
    symbolId: 'icon-[dir]-[name]',})]. })Copy the code

A simple SvgIcon component has been packaged to read SVG directly from a file and automatically find files based on the folder directory.

<template>
  <svg aria-hidden="true" class="svg-icon-spin" :class="calsses">
    <use :xlink:href="symbolId" :fill="color" />
  </svg>
</template>

<script lang="ts" setup>
const props = defineProps({
  prefix: {
    type: String.default: 'icon',},name: {
    type: String.required: true,},color: {
    type: String.default: '# 333',},size: {
    type: String.default: 'default',}})const symbolId = computed(() = > ` #${props.prefix}-${props.name}`)
const calsses = computed(() = > {
  return{[`sdms-size-${props.size}`]: props.size,
  }
})
const fontSize = reactive({ default: '32px'.small: '20px'.large: '48px' })
</script>
Copy the code

πŸ“¦ supportAxios (ts)

Already encapsulates the mainstream of the interceptor, request to invoke methods such as index to distinguish between the modules. The ts/status. The ts/type ts

/ / encapsulation SRC/API/user/index. The ts
import request from '@utils/http/axios'
import { IResponse } from '@utils/http/axios/type'
import { ReqAuth, ReqParams, ResResult } from './type';
enum URL {
    login = '/v1/user/login',
    permission = '/v1/user/permission',
    userProfile = 'mock/api/userProfile'
}
const getUserProfile = async () => request<ReqAuth>({ url: URL.userProfile });
const login = async (data: ReqParams) => request({ url: URL.login, data });
const permission = async () => request<ReqAuth>({ url: URL.permission });
export default { getUserProfile, login, permission };
Copy the code
/ / call
import userApi from "@api/user"
// Components can be referenced directly in setup mode
const res = await userApi.profile()
Copy the code

πŸ‘½ Automatically generatedrouter, the filteringcomponentscomponent

Vue-router4.0 supports modularization. Routes can be automatically generated by searching the Pages folder, and dynamic routes are supported

import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import routes from 'virtual:generated-pages'

console.log(routes,'Print to generate automatically generated routes')
// Import the generated routing data
const router = createRouter({
  history: createWebHashHistory(),
  routes,
})

export default router
Copy the code

🧬 supports Mock data

Use the viet-plugin-mock plug-in to enable automatic differentiation and start-stop environment configuration

// vite config
viteMockServe({
    ignore: / ^ \ _ /,
    mockPath: 'mock'.localEnabled: !isBuild,
    prodEnabled: false.// https://github.com/anncwb/vite-plugin-mock/issues/9
    injectCode: ` import { setupProdMockServer } from '.. /mock/_createProdMockServer'; setupProdMockServer(); `
    })
Copy the code

Root directory to create _createProductionServer ts file, non _ opening files are automatically loaded into the mock

import { createProdMockServer } from 'vite-plugin-mock/es/createProdMockServer';
// Batch load
const modules = import.meta.globEager('./mock/*.ts');

const mockModules: Array<string> = [];
Object.keys(modules).forEach((key) = > {
    if (key.includes('/ _')) {
        return; } mockModules.push(... modules[key].default); });export function setupProdMockServer() {
    createProdMockServer(mockModules);
}
Copy the code

🎎 Proxy agent

// vite config
import proxy from '@config/vite/proxy';
export default defineConfig({
    ...
    server: {
        hmr: { overlay: false }, // Set server.hmr.overlay to false to disable the server error mask layer
        // Service configuration
        port: VITE_PORT, // Type: number Specifies the server port.
        open: false./ / type: Boolean | string on server startup automatically open in a browser application;
        cors: false./ / type: Boolean | CorsOptions CORS for development server configuration. Any source is enabled and allowed by default
        host: '0.0.0.0'.// IP configuration, support from IP boot
        proxy,
    }
    ...
})
Copy the code
// proxy.ts
import {
    API_BASE_URL,
    API_TARGET_URL,
    MOCK_API_BASE_URL,
    MOCK_API_TARGET_URL,
} from '@config/constant';
import { ProxyOptions } from 'vite';
type ProxyTargetList = Record<string, ProxyOptions>;

const init: ProxyTargetList = {
    // test
    [API_BASE_URL]: {
        target: API_TARGET_URL,
        changeOrigin: true.rewrite: (path) = > path.replace(new RegExp(` ^${API_BASE_URL}`), ' '),},// mock
    [MOCK_API_BASE_URL]: {
        target: MOCK_API_TARGET_URL,
        changeOrigin: true.rewrite: (path) = > path.replace(new RegExp(` ^${MOCK_API_BASE_URL}`), '/api'),}};export default init;

Copy the code

πŸŽ‰ other

  • πŸ— supportvw/vhMobile layout is compatible and can also be usedplopConfigure the build file yourself
  • There are more new features addedcommitingIf you have a better solution welcomePR

Tool library

Learn to use the appropriate tool library, make coding twice the result. Open source libraries, in particular, are worth everyone learning, because that’s the level you should be at. Here are some commonly used libraries for large factories, because I like new… , the following tools can be directly introduced.

JS library

  • PNPM, a tool that relies on package global management, the boss no longer need to worry about my C drive is not enough. Vite official recommendation, byte official front-end team large-scale project test
  • Mitt Global Event listener library, Vue3 official recommendation
  • Hammer, which recognizes gestures made by touch, mouse, and pointer events, is only 7.34 KB
  • outils, a set of functions commonly used in development, can also be usedlodash
  • Day. js, TailWindcss, vue-cookiesI won’t list them until you see too many

UI library

  • arco-design, new UI framework from byte team, more flexible configuration level,fast-vue3This is what you use, and if you don’t like it, you can remove it
  • Semi-design, a framework from the front of Douyin, is for UI and FE, which often quarrel with each other
  • Nutui, the UI framework produced by jd’s front end team, has been upgraded to 3.x. I think the appearance level is the highest and accept refutation
  • Naive – UI, TypeScript syntax, theme tunable, this company is awesome
  • That’s all for now. I’ll fill it up when I get sleepy

data

  • Official Configuration Document Entry Vite, Pinia, Vue-Router4, plop…
  • Vu3 Write Components :juejin.cn/post/705271…
  • Some special configurations :juejin.cn/post/705431…

The last

Water group of friends

  • Welcome to join the front water friends group, paddling, everyone paddling together, now the fan group rarely discuss technology, so let’s swim together. Welcome to my public account sweeping the floor blind monk.
  • Cutting-edge technology, all kinds of experience, interactive related technology, all kinds of translation, research newspaper perspective in advance.
  • White piao, promise to release all paid resources, fans all free white piao, otherwise we who have time to play with you, hey hey.