Use require.context() in Vue to automatically generate routes

In actual development, adding a new page may require rewriting the routing problem, which results in the routing file having to be re-edited every time. There are many pages and the modification is more complicated.

So is there any way to simplify this import or export operation? The answer is yes, let me introduce require.context to you below

In the past, we introduced routes through import.

import HomeView from '../views/HomeView.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView
  },
  {
    path: '/about',
    name: 'about',
    component: () => import('../views/AboutView.vue')
  }
]

This is very painful, because every time you add a page, you may have to write so many lines. Can such regular things be completed automatically?

require.context (requires vue-cli3+ version)

You can also create your own context through the require.context() function.

Three parameters can be passed to this function: a directory to search, a flag indicating whether its subdirectories should also be searched, and a regular expression to match files.

Webpack will resolve require.context() in your code during the build.

The syntax is as follows:

require.context(directory, useSubdirectories, regExp)
  1. directory: the file path to search for
  2. useSubdirectories: whether to search for subdirectories
  3. regExp: the regular pattern to match the file

Example:

require.context('./test', false, /\.test\.js$/);
//(创建出)一个 context,其中文件来自 test 目录,request 以 `.test.js` 结尾。
1. Create the autoRouter.js file under the router file.
let routerArr = []

//查找views目录,以.vue结尾的文件,查找子目录
const contexts = require.context('../views/', true, /\.vue$/)

contexts.keys().forEach(value => {
  const path = value.substr(value.indexOf('/'), value.lastIndexOf('.') - 1)
  const componentLocation = value.substr(value.indexOf('.') + 1, value.lastIndexOf('.') - 1)
  const componentName = componentLocation.substr(componentLocation.lastIndexOf('/') + 1)
  //添加到路由数组中
  routerArr.push({
    path: path,
    name: componentName,
    component: () => import(`@/views${componentLocation}`)
  })
})

export default routerArr
2.Introduce the autoRouter.js file into the index.js file under the router file
import Vue from 'vue'
import VueRouter from 'vue-router'

//引入刚刚写的autoRouter.js文件
import routerArr from './autoRouter.js'

Vue.use(VueRouter)
const routes = [
 //这里是其他手动写的路由
]

const router = new VueRouter({
  mode: 'history',
  //这里进行路由合并
  routes:[...routes,...routerArr]
})

export default router
3. Once completed, create a new page in views later, so there is no need to manually write routes.
Summarize

We can automatically introduce files through require.context.
In fact, we are not limited to components and routing, all module files are universal.

Guess you like

Origin blog.csdn.net/shanghai597/article/details/131918906