current position:Home>The front end automatically generates routes

The front end automatically generates routes

2021-08-27 04:56:19 Biscuits_

Preface

Under the engineering trend of large front-end , Automation has also become an integral part of the front end , Automation improves a lot of efficiency in our daily development and can reduce a lot of code , Single configuration json File can generate a series of desired code, which is the ultimate goal of developers , This chapter will be based on react Talk about how to pass json The file generates the corresponding route .

preparation

Before we start , Check your version first ( I'm based on react Of ,vue It's the same with ):

  1. react >= 16
  2. npm <= 11 ( The main question is 10.15.3)
  3. gulp 3.9.1(3.+)

Because of the higher version of node Will be with me at present gulp There will be a conflict between the versions of , So make sure npm The version should be lower than 11, have access to nvm Conduct node The version of the tube Make sure you can switch freely node edition .

Route writing

Usually we write react Route through react-router-dom Provides a way to write , And equipped with some lazy loading and other optimization processing .

import React, { Suspense, lazy } from "react";
import { Route, Switch } from "react-router-dom";
const loading = true;
const router = (
    <Suspense fallback={loading}> <Switch> <Route path="/operator/list" exact component={lazy(() => import("../view/operator/list/app") )} /> </Switch> </Suspense>
)

 Copy code 

Above , New routes will be added later , Continue to add later , But when the number of routes is large , The repetitive operations we do are a little frequent . When there are too many repetitions , It is suitable to use automation to make the project more flexible .

Automatically generate routes

utilize glup as well as glup-rename To complete our automated generation , actually node You can also complete ,node It's pretty good as a front-end tool , But here we mainly describe the use of glup To complete .

Before we start , First, we need to define the necessary templates , Like the home page 、404 Page, etc. .

//  Define routing templates 
const routerTemplates = ` import React, { Suspense, lazy } from 'react' import { Route, Switch } from 'react-router-dom' const Home = lazy(() => import('../view/home/app')) const NoMatch = lazy(() => import('../view/error/404.jsx')) const loading = true {$$ImportComponent$} const router = ( <Suspense fallback={loading}> <Switch> {$$SubRoutes <Route path="/" exact$} component={Home}/> <Route path="*" component={NoMatch}/> </Switch > </Suspense> ) export default router `
//  Define the generation route occupation 
const subRouteTemplate = ` <Route path="{$$route$}" exact component={lazy(() => import('../view{$$path$}/app'))}/> `
//  Define the to be resolved json
const MENUS_PATH = './src/static/app/js/route/menus.json'
//  Define the output directory 
const MUNUS_DEST_PATH = './src/static/app/js/route/'
 Copy code 

After defining the template , We make use of through2 To deal with the flow , And placeholders to replace the route we want .

const through = require('through2')

function generateRoutes() {
  const subLoader = []
  const subRoutes = []
  return through.obj((file, enc, cb) => {
    const list = JSON.parse(file.contents.toString())
    list.map((menu) => {
      menu.items.map((item) => {
        item.routes.map((route) => {
          subRoutes.push(
            subRouteTemplate
              .replace('{$$route$}', route.route)
              .replace('{$$name$}', route.name)
              .replace('{$$path$}', route.path)
          )
        })
      })
    })

    const final = routerTemplates
      .replace('{$$ImportComponent$}', subLoader.join(''))
      .replace('{$$SubRoutes$}', subRoutes.join(''))
    file.contents = Buffer.from(final)
    return cb(null, file)
  })
}
 Copy code 

Finally, we use glup To define the task , The route can be generated automatically through command execution .

gulp.task('generate-routes', () => {
  return gulp
    .src(MENUS_PATH)
    .pipe(generateRoutes())
    .pipe(rename('routes.jsx'))
    .pipe(gulp.dest(MUNUS_DEST_PATH))
})
 Copy code 

Complete code :

/* eslint-disable array-callback-return */
const gulp = require('gulp')
const through = require('through2')
const rename = require('gulp-rename')

const MENUS_PATH = './src/static/app/js/route/menus.json'
const MUNUS_DEST_PATH = './src/static/app/js/route/'

const routerTemplates = ` import React, { Suspense, lazy } from 'react' import { Route, Switch } from 'react-router-dom' const Home = lazy(() => import('../view/home/app')) const NoMatch = lazy(() => import('../view/error/404.jsx')) const loading = true {$$ImportComponent$} const router = ( <Suspense fallback={loading}> <Switch> {$$SubRoutes <Route path="/" exact$} component={Home}/> <Route path="*" component={NoMatch}/> </Switch > </Suspense> ) export default router `

const subRouteTemplate = ` <Route path="{$$route$}" exact component={lazy(() => import('../view{$$path$}/app'))}/> `
function generateRoutes() {
  const subLoader = []
  const subRoutes = []
  return through.obj((file, enc, cb) => {
    const list = JSON.parse(file.contents.toString())
    list.map((menu) => {
      menu.items.map((item) => {
        item.routes.map((route) => {
          subRoutes.push(
            subRouteTemplate
              .replace('{$$route$}', route.route)
              .replace('{$$name$}', route.name)
              .replace('{$$path$}', route.path)
          )
        })
      })
    })

    const final = routerTemplates
      .replace('{$$ImportComponent$}', subLoader.join(''))
      .replace('{$$SubRoutes$}', subRoutes.join(''))
    // eslint-disable-next-line no-param-reassign
    file.contents = Buffer.from(final)
    return cb(null, file)
  })
}

gulp.task('generate-routes', () => {
  return gulp
    .src(MENUS_PATH)
    .pipe(generateRoutes())
    .pipe(rename('routes.jsx'))
    .pipe(gulp.dest(MUNUS_DEST_PATH))
})

 Copy code 

Configure routing json file :

[
  {
    "text": " Management system ",
    "key": "mng",
    "items": [
        {
            "key": "operator",
            "text": " Operator, ",
            "routes": [
                  {
                    "title": " Commodity management ",
                    "name": "product_mng",
                    "route": "/operator/product/list",
                    "path": "/operator/product/product_mng/list"
                  }
            ]
        }
    ]
  }
]
 Copy code 

Then execute the command on the console generate-routes You can generate a route .

Last

There is more than one similar method , You can also use node The read / write stream of ,webpack There are also methods to get context api, Such as require.context etc. .

If it helps you , I hope you will be generous for three times ~

copyright notice
author[Biscuits_],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210827045616254t.html

Random recommended