webpack require.context

复制代码
require.context(
  (directory: String),
  (includeSubdirs: Boolean) /* 可选的,默认值是 true */,
  (filter: RegExp) /* 可选的,默认值是 /^\.\/.*$/,所有文件 */,
  (mode: String)  /* 可选的, 'sync' | 'eager' | 'weak' | 'lazy' | 'lazy-once',默认值是 'sync' */
)

指定一系列依赖项,通过使用 directory 的路径,以及 includeSubdirsfilter 选项,进行更细粒度的模块引入,使用 mode 定义加载方式。以此可以很容易的解析模块:

复制代码
var context = require.context('components', true, /\.html$/);
var componentA = context.resolve('componentA');

如果 mode 设置为 lazy,基础模块将以异步方式加载:

复制代码
var context = require.context('locales', true, /\.json$/, 'lazy');
context('localeA').then((locale) => {
  // do something with locale
});

mode 的可用模式及说明的完整列表在 import() 文档中进行了描述。

  • keys {Function} -返回匹配成功模块的名字组成的数组
  • id {String} -执行环境的id,返回的是一个字符串。
  • resolve {Function} -接受一个参数request,request为检索的文件夹下面匹配文件的相对路径,返回这个匹配文件相对于整个工程的相对路径

生成自动路由用例:

const reqRouter = require.context('@/views', true, /\.vue$/)

javascript 复制代码
// 自动加载路由
const autoLoadRoutes = [];
 
// 自动加载
reqRouter.keys().forEach(key => {
  let reqRouterDefault = reqRouter(key).default
  if (!reqRouterDefault.commonComponent) {      //公共组件不参与路由配置,公共组件配置true
    let fileUrl = key.replace(/\.\//g, '')//匹配路径
    let routePath = fileUrl.split('.')[0];
    autoLoadRoutes.push({
      path: `/${routePath}`,
      name: routePath,
      meta: {
        title: reqRouterDefault.title,
        keepAlive: reqRouterDefault.keepAlive
      },
      component: () => import(`@/views/${fileUrl}`)
    })
  }
})
// 全部路由信息
const routes = [
  {
    path: '/',
    redirect: 'home'
  },
  {
    path: '/home',
    name: 'home',
    component: () => import('@/views//Home.vue')
  },
  {
    path: '/401',
    name: '401',
    component: () => import('@/views//Unauthorized.vue')
  },
  ...autoLoadRoutes,
]

store合成用例:

store js中的代码示例

javascript 复制代码
const state = {
  test: 0
}

const mutations = {
  CHANGE_TEST: (state, payload) => {
    state.test= payload
  }
}

const actions = {}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
相关推荐
Htr_2 分钟前
Vercel 使用指南:框架、工作流与基础设施一体化的现代 Web 部署平台
前端
一颗烂土豆16 分钟前
ECharts 太平面?试试这款 Vue 3D 图表库
前端·vue.js·echarts
anyup24 分钟前
迁移uni-app x,我是如何让 AI 把我一步步搞崩溃的...
前端·uni-app·trae
用户9210802628632 分钟前
从读框架到搭项目:基于 Ant Design X Vue 和 RICH 范式搭建 AI 前端工作台
前端
Hilaku33 分钟前
为什么同一段代码在 Safari 上永远有 Bug?
前端·javascript·程序员
半仙er38 分钟前
第二周06天 Vue3 + TypeScript 实战与本周复盘
前端
heyCHEEMS40 分钟前
切页回来组件消失了?一个浏览器渲染机制引起的容器高度坍塌 bug
前端·浏览器
张元清41 分钟前
React scrollIntoView + useRef:滚动到指定元素 (2026)
javascript·react.js
iaku41 分钟前
Prompt 不是玄学:写给前端的 Prompt 工程指南
前端·人工智能
爱丶不疚41 分钟前
在 dsh 仓库里扒到的宝藏工作流:详解 .agents/notes 决策沉淀系统
前端·agent·vibecoding