This article has participated in the activity of “New person creation Ceremony”, and started the road of digging gold creation together.

background

Due to the business attribute of toB, there are many pages with highly repetitive lists, details, popboxes and other pages between the systems, so this scaffold is precipited from 20+ projects. Currently, 5+ systems are in use, and there will be long-term maintenance in the future. Welcome to have it

The length is a little long, it is suggested to collect first, if you feel helpful, give a star, thank you ~ in the background front-end scaffolding GitHub address

positioning

Vue. Js 2.x and ant-design-Vue component libraries are a unified front-end scaffolding for rapid construction of back-end systems.

compatibility

Google Chrome Firefox Safari Edge browser IE11
Square root Square root Square root Square root Square root

Feature list

The module Function is introduced The progress of
Dynamic routing Back end to return to the menu structure front-end rendering, support one-click switch to static routing Square root
Static routing Static routes written to the front end can be switched to dynamic routes by one click Square root
The menu Support to expand and fold, black and white theme switch, support left and top two layouts, to meet the needs of a variety of business styles Square root
layout Different layouts are built in, and the new layouts can handle most scenarios Square root
Access control Support control menu explicit hidden, button explicit hidden, the front end of the data structure has certain requirements, can agree small changes, authority control like a duck to water Square root
General page Built-in 403, 404, 500 pages, so that the system is more user-friendly Square root
Error trapping You can enable and disable error logs with one click, and manage error detection and location visually Square root
request Based on AXIos, support for file upload, download, automatic header detection, custom recognition of mockUrl and URL, support for multi-domain list domain names, covering the vast majority of usage scenarios as a request Square root
Tool library Built-in variable type judgment, UUID generation, common phone number, ID card, password verification and other common functions, can be called globally, convenient and quick Square root
Custom extension Contains extensions to vue. prototype, custom instructions, component libraries, etc., global add instructions and functions more unified Square root
packaging Support private cloud packaging (Intranet environment) and non-private cloud packaging, one click on and off, do not need to pay attention to the complex WebPack configuration Square root
Mock services Mocker-api and MockJs2 are built in and compatible for different usage scenarios, requiring only one mock writing method instead of waiting for an interface to be provided Square root
eslint Strict and complete ESLint rules are built in to ensure code specification and more efficient co-development Square root
store Built-in store, can directly obtain user information, global configuration, and so on, for use Square root
The user center With built-in login, registration and password retrieval pages, the account system can be built simply by connecting to the back-end interface Square root
Many environmental Built-in preview environment, demo environment, test environment, formal environment packaging configuration, can meet the requirements of multi-environment packaging deployment Square root
Template library Provides a set of template library to create pages quickly, development efficiency significantly improved Square root
Unit testing Integrate complete test cases to make scaffolding more robust feature

The project structure

. ├ ─ ─ the README. Md# Please fuck me for free before you do anything├ ─ ─ Babel. Config. Js ├ ─ ─ the config# Project configuration│ ├ ─ ─ config. Js# The custom configuration provided for use with vue.config.js is removed from the relatively independent parts│ ├ ─ ─ project. Config. JsThe configuration items provided to the Node.js deployment package│ └ ─ ─ theme. The plugin. Js# theme configuration, used when customizing theme configuration├ ─ ─ jsconfig. Json ├ ─ ─ the mock# Mock data service│ ├─ Index.js │ ├─ modulesAll mock data is defined here│ └ ─ ─ utils. Js# Built-in utility functions for handling mock data├ ─ ─ package. Json ├ ─ ─ public │ ├ ─ ─ the favicon. Ico │ └ ─ ─ index. The HTML ├ ─ ─ server# Node.js deploys package middleware│ ├─ ├─ SRC# source directory│ ├ ─ ─ API# request│ ├ ─ ─ app. Less# Public style│ ├ ─ ─ app. Vue# the root component│ ├ ─ ─ assets# static resources│ ├ ─ ─ the components# components│ ├ ─ ─ extends# Extensions, including extensions to vue. prototype, custom instructions, component libraries, etc│ ├ ─ ─ layouts# layout│ ├ ─ ─ the main js# import file│ ├ ─ ─ the router# Route configuration│ ├ ─ ─ store# store configuration│ ├ ─ ─ utils# tool library│ └ ─ ─ views# page├ ─ ─ tests# Unit tests│ ├─ ├─ vue.config.js# vue- configuration file provided by cli└ ─ ─ yarn. The lockCopy the code

Project configuration

The environment variable

Scaffolding has agreed on a configuration of environment variables, which are used to switch and support various functions. The functions of each variable are as follows:

BASE_URL

The route address prefix is an environment variable provided by vue-CLI. The effect is the same as publicPath in vue.config.js. You are strongly advised to change the BASE_URL variable if you need to change publicPath.

VUE_APP_API_PREFIX

The url prefix of the request interface can be changed as provided by the backend development. If the prefix is not required, set it to /.

VUE_APP_LS_PREFIX

Scaffolding has a built-in vue-ls library to operate on storage. This variable is the namespace field configuration.

VUE_APP_PRIVATE

If the project uses few components, you can also set this parameter to True to reduce unnecessary CDN resource loading. If you use the custom theme function, you must set this parameter to true; otherwise, the custom theme does not take effect after being packaged.

VUE_APP_USE_MOCKER

Mocker-api (network requests can be seen) and Mockjs2 (network requests cannot be seen) are built in. Set to true to mocker-API and set to false to mockjs2.

VUE_APP_BUILD_ENV

Package environments and deploy to different production environments. The default is Production, which has built-in configurations for preview, test, demo, and production environments in package.json, and you can add more configurations based on your business.

VUE_APP_THEME_COLOR

The default theme color is to follow ant-design-vue theme color # 1890FF. When customizing the theme color, the main color value only needs to be changed in this one place. Then configure the custom theme variable in the modifyVars field under config/config.s. Changes related to custom theme colors generally only need to be made in these two areas.

VUE_APP_BUILD_REPORT

Whether to enable packaging analysis. When the packaged Dist resource file is found to be very large, set it to true, and the visual analysis page of this packaging will be opened automatically after each packaging.

In addition to the above environment variables, scaffolding is based on vue.config.js configuration capabilities provided by VUE-CLI and encapsulates the capabilities for package optimization, theme configuration, and interface proxy configuration.

Packaging optimization

When VUE_APP_PRIVATE is set to false, common third-party libraries are automatically ignored during packaging and loaded using CDN, which reduces the size of packaged resources and improves the packaging speed.

Setting VUE_APP_PRIVATE to true packs all resources into DIST, while doing a simple split of third-party libraries to reduce the size of individual files.

The topic configuration

Support for custom theme colors is encapsulated in config/theme.config.js and used with the VUE_APP_THEME_COLOR variable.

Interface Proxy Configuration

Configure the interface request address in the proxy field of config/theme.config.js.

{
  // System default prefix configuration
  [apiPrefix]: {
    target: 'http://127.0.0.1:7001'.ws: false.changeOrigin: true
  },
  // Configure the user-center interface prefix
  '^/account': {
    target: 'http://account.example.com'.ws: false.changeOrigin: true.pathRewrite: {
      '^/account': ' '}}}Copy the code

custom

After the project is started, there will always be a “Customize” button on the right. The complete configuration items after expansion are as follows:

Here you can set the menu style, theme color and navigation mode for quick preview. After confirming the final configuration, you can synchronize the modification in SRC /store/modules/app.js. The complete configuration items supported are as follows:

{
  /** * The image address of the logo, the default is @/ /assets/logo.svg */
  logo,
  /** * The slogan */ next to the logo
  slogan: 'Middle background front end scaffolding'./** * Menu theme, default is dark theme * dark: dark theme * light: light theme */
  menuTheme: Vue.ls.get(types.MENU_THEME, 'light'),
  /** * Vertical: inline: inline: horizontal: top navigation menu */
  menuMode: 'inline'./** * Layout mode * side: left/right layout, navigation menu on the left * top: up/down layout, navigation menu on the top */
  layout: Vue.ls.get(types.LAYOUT, 'side'),
  /** * The default theme color, following the ant-design-vue library */
  themeColor: Vue.ls.get(types.THEME_COLOR, process.env.VUE_APP_THEME_COLOR),
  /** * Routing mode * static: static. In static mode, routes are added, deleted, or modified in SRC /router/route-static.js. In dynamic mode, routes are added, deleted, and modified in SRC /router/route-dynamic. Each time * a new route page is added to routeComponents, the route menu */ is updated in the backend
  routeMode: 'dynamic'./** * menu expansion state */
  menuCollapsed: Vue.ls.get(types.MENU_COLLAPSED, false),
  /** * Navigation mode * breadcrumb: navigation * TAB: navigation */
  navMode: Vue.ls.get(types.NAV_MODE, 'breadcrumb'),
  /** * If you need to catch error logs, see SRC /core/extends
  catchError: Vue.ls.get(types.CATCH_ERROR, false)}Copy the code

This “custom” entry will be hidden automatically after the official environment package goes live

request

Complete request configuration items are as follows:

The field name annotations
url Request an address, preferentially if a URL is defined, otherwise use mockUrl, which does not start with a slash by default, and does not concatenate if it starts with a slashVUE_APP_API_PREFIXvariable
mockUrl Mock service request address, used as defined
method The request mode can be GET, POST, PUT, and DELETE
data In the case of POST, the data method passes a JSON parameter, which can be used with the following params field
params The parameter passed is a string, concatenated after the URL, similar/a/b? id=1&type=2This way, if it’s a GET request, you can only pass parameters through Params
headerType Request header type, default isjson, the correspondingContent-Typeapplication/jsonTo set upformThe time,Content-Typeapplication/x-www-form-urlencoded; charset=UTF-8To set upupload.Content-Typemultipart/form-dataTo set updownload.headers.resTypeblob, will automatically download the file, cooperatefileNameField custom download file name, set toblobReturns file flow information
fileName Cooperate withheaderTypeIs equal to thedownloadIs used to customize the name of the downloaded file
closeAutoTips By default, a backend error is thrown after a request fails,closeAutoTipsSet totrueYou can turn this behavior off

Request code configuration

Example:

// Initiate a POST request with data and params parameters, and turn off autoprompt
export function queryTableList (data) {
  return request({
    // The VUE_APP_API_PREFIX prefix is automatically concatenated when the URL does not start with a /
    url: 'table/list'.mockUrl: '/mock/table/list'.method: 'post',
    params,
    data,
    // Set the request type
    headerType: 'json'.// Turn off autoprompt
    closeAutoTips: true})}// Initiate a GET request
export function queryGetDemo (params) {
  return request({
    VUE_APP_API_PREFIX is automatically ignored when the VUE_APP_API_PREFIX configuration begins with a /. This usage scenario is usually accompanied by setting the proxy
    url: '/account/table/list'.method: 'get',
    params
  })
}
// post requests to download the file
export function queryDownloadDemo (data) {
  return request({
    url: 'file/download'.method: 'post'.// Set this parameter to Download files. The file download action is encapsulated internally. After this parameter is invoked, files are automatically downloaded without further processing
    headerType: 'download'.// Specify the name of the file to download
    fileName: 'Front end to give up. PDF'.// Parameter passing
    data
  })
}
// Get file stream custom processing
export function queryContentBlob (data) {
  return request({
    url: 'file/download'.method: 'post',
    data,
    headerType: 'blob'
  })
    .then(blob= > {
      // Blob file flow information, can be customized})}Copy the code

Using a Mock Service

Before the back end provides an interface, the front end can customize the fake data required by the page. Add a select.js to mock/modules and define a mock data:

const selectData = [
  { value: '1'.label: 'normal' },
  { value: '2'.label: 'disabled'}]module.exports = {
  'POST /select/list': selectData
}
Copy the code

Then in mock/index.js we introduce:

const select = require('./modules/select')
constdata = { ... addPrefix(select) }Copy the code

Then define the method to call the interface in SRC/API /select.js:

// Get the drop-down list
export function querySelectData (params) {
  return request({
    mockUrl: '/mock/select/list'.method: 'get',
    params
  })
}
Copy the code

Finally, use the import on the page that needs to use the request.

  • Used in template:
<ak-select :loadData="querySelectData" />
Copy the code
  • Use in js:
querySelectData()
  .then(res= > {
    this.selectData = res.data || []
  })
Copy the code

Routes and Menus

Routes are classified into static and dynamic routes. Static routes are configured on the front end and the front end is responsible for routing control. In dynamic routing, the back end interface returns a menu list, and the front end parses and generates the final route according to the convention rules. To switch between the two, just change the routeMode value in SRC /store/modules/app.js.

{
  /** * Routing mode * static: static. In static mode, routes are added, deleted, or modified in SRC /router/route-static.js. In dynamic mode, routes are added, deleted, and modified in SRC /router/route-dynamic. Each time a new route page is added to routeComponents, the route menu */ is updated in the backend
  routeMode: 'dynamic'
}
Copy the code

Routing configuration items are as follows:

The field name annotations
path Access paths, no slashes, relative paths, will eventually be assembled into absolute paths
component The corresponding component, static route this value is an import of a page object, dynamic route isrouteComponentsThe key defined inside
title The title of the current page is displayed in the breadcrumb navigation and menu navigation
icon Only the Icon Icon in front of the menu will be set in this top-level menu. Currently, the supported Icon is in the Icon component of ANTD. If you want to customize the Icon, you need to introduce the custom Icon component
meta The meta information of the route, if it’s a static route, is contained heretitle,icon,hidden,target,hrefhideChildrenThese six fields
hidden Set whether the current route is displayed in the menu navigation
hideChildren Sets whether the child routes of the current route are displayed in the menu navigation
children Zi lu by

A complete static route would look like this:

[{
  path: '/'.// Component always points to a referenced vue page file
  component: LayoutBase,
  redirect: '/dashboard/workplace'.children: [{
    path: 'dashboard'.component: LayoutBlock,
    title: 'home'.icon: 'dashboard'.children: [{
      path: 'workplace'.component: () = > import('@/views/dashboard/workspace.vue'),
      title: 'Workbench'}]}, {path: 'list'.component: () = > import('@/views/table/list.vue'),
    title: 'list'.icon: 'list'}]}, {path: '/user'.component: LayoutUser,
  title: 'User center'.icon: 'user'.children: []}]Copy the code

A relatively complete dynamic route would look like this:

[{
  id: 1.parentId: 0.sort: 1.path: '/'.// Component always points to a string defined in the routeComponents SRC /router/route-dynamic.js file
  component: 'LayoutBase'.redirect: '/dashboard/workplace'.children: [{
    id: 2.parentId: 1.sort: 1.path: 'dashboard'.component: 'LayoutBlock'.title: 'home'.icon: 'dashboard'.children: [{
      id: 3.parentId: 2.sort: 1.path: 'workplace'.component: 'workspace'.title: 'Workbench'.icon: null}]}, {id: 4.parentId: 1.sort: 1.path: 'list'.component: 'tableList'.title: 'list'.icon: 'list'}]}, {id: 5.parentId: 0.sort: 1.path: '/user'.component: 'LayoutUser'.title: 'User center'.icon: 'user'.children: []}]Copy the code

In real business, there may be hidden, Target, createdAt, and other fields, which can be added as needed.

permissions

Scaffolding support button level access control, only need in the current login user information (SRC/store/modules/user. Js) returned in the corresponding access points. For example, if the current user has the edit, add, and delete permissions on the list page, the corresponding permissions are as follows:

{
  permissions: ['listAdd'.'listDelete'.'listEdit']}Copy the code

Control the display of action buttons on the list page by using:

 <a-button v-action.listAdd>add</a-button>
 <a-button v-action.listDelete>delete</a-button>
Copy the code

You can also use the $auth method to control:

if (this.$auth('listEdit')) {
  // Edit
}
Copy the code

style

Scaffolding has a style library built in. The style library uses documentation.

Scaffolding also adds ant-design-vue theme variables to the global, which you can use in any less, like this:

.ant-card {
  color: @main-color ! important;
}
.C-FAIL {
  color: @error-color;
}
Copy the code

The full less variable

At the same time, the scaffolding in order to facilitate extension also custom part less variable, can be in SRC/components/index found less.

Using template libraries

Scaffolding has developed a set of matching template library, can easily create various components and pages, greatly improve the efficiency of development. Template libraries use documentation

release

Scaffolding has built-in production environment, test environment, demo environment and preview environment, commands are configured, can directly execute the corresponding commands for packaging:

# Production environment packaging
yarn build

# Test environment package
yarn build:test

# Demo environment package
yarn build:demo

# Preview environment package
yarn build:preview
Copy the code

The preview environment is the scaffolding’s own environment, which packages “custom” functionality.

The deployment of

Deploy to the back-end server

Copy the packaged Dist static resources directly to the corresponding back-end static resource directory. For example Java back-end words can in SRC/main/resources/static, or in the SRC/main/webapp.

Deploy to the Nginx server

Copy the packaged Dist static resources directly to the static resource directory specified by nginx.

Deploy using wy App

The wy command is provided by the Wy-CLI. Wy – CLI usage documents

You need to run YARN Build to package the dist static resource package, and then run wy tar to package it into a Node.js deployment package.

Then upload the deployment package to the back-end server, decompress the package, and run the WY app command in the root directory to start the package.

Wy See config/project.config.js for the configuration file used to start the wy app.

Create scaffolding using Wy-CLI

Global installation:

npm i @wytxer/wy-cli -g
Copy the code

Then run wy init project-name to install scaffolding and select background scaffolding from the list:

❯ Middle background front-end scaffolding (vue.js 2.x + Vue Router + Vuex + Ant Design Vue)Copy the code

Scaffolding common commands:

# installation
yarn install

# Start the development service
yarn serve

# Production environment packaging
yarn build

# Test environment package
yarn build:test
Copy the code

Code and documentation

The length is long, thank you for reading, scaffolding will be long-term maintenance, welcome to download and use: middle background front-end scaffolding GitHub address

Scaffolding usage documentation is also kept up to date.