Vue中使用require.context自动引入组件的方法介绍

我们项目开发中,经常需要import或者export各种模块,那么有没有什么办法可以简化这种引入或者导出操作呢?答案是肯定的,下面就为大家介绍一下require.context

require.contextwebpack 提供的一个 API,用于创建 context,即一组具有相同上下文的模块。

使用 require.context 可以方便地加载多个模块,并且可以灵活地控制模块的加载顺序和依赖关系。

以前我们都是通过import 方式引入组件

javascript 复制代码
import A from 'components/A'
import B from 'components/B'
import C from 'components/C'
import D from 'components/D'

这样很蛋疼,因为每加一个组件,可能都要写这么一句,这样有规律的事,是否可以通过自动化完成?

require.context (需要vue-cli3+的版本)

javascript 复制代码
require.context(directory, useSubdirectories, regExp)
  1. directory: 要查找的文件路径
  2. useSubdirectories: 是否查找子目录
  3. regExp: 要匹配文件的正则

1.在compoents文件下随便创建index.js文件

javascript 复制代码
const requireComponent = require.context('./', true, /\.vue$/)
const install = (Vue) => {
    if (install.installed) return
    install.installed
    requireComponent.keys().forEach(element => {
        const config = requireComponent(element)
        if (config && config.default.name) {
            const componentName = config.default.name
            Vue.component(componentName, config.default || config)
        }
    });
}

if (typeof window !== 'undefined' && window.Vue) {
    install(window.Vue)
}

export default {
    install
}

2.mian.js引入该js

javascript 复制代码
import install from './compoents'
Vue.use(install)

总结

我们可以通过require.context可以自动化引入文件。

其实我们不单单局限于组件,路由内, 所有模块文件都是通用的, 例如路由, 接口封装模块,都是可以使用的。

相关推荐
小七-七牛开发者6 天前
TokenPilot:让 LLM Agent 长会话成本降 60%+ 的上下文管理
缓存·agent·token·context·上下文·推理成本
HYDtomako14 天前
Prompt,Context,Harness Engineer总结
context·prompt engineer·harness·contextengineer
从心开始38218 天前
机房建设怎样一次到位不花冤枉钱
模块·机房·改造
小七-七牛开发者19 天前
AI Agent 的 4 个工程关键词:Prompt、Context、Loop、Harness 到底是什么?
ai·大模型·agent·token·context·loop·codex·harness
雪碧聊技术19 天前
python核心语法:模块
python·模块·
故渊at24 天前
第一板块:Android 系统基石与运行原理 | 第五篇:Context 上下文与资源配置体系
android·人工智能·opencv·context·上下文·资源配置体系
Hi~晴天大圣1 个月前
AI Engineer发展历程
prompt·context·harness
华普微HOPERF1 个月前
LoRa模块,如何通过卫星通信补齐地面网络的覆盖盲区?
网络·嵌入式硬件·模块·卫星通信
曲幽1 个月前
写页面时别再把 Element Plus 整个搬进来啦!Vue3按需加载的坑我帮你踩平了
vue3·web·vite·icon·element plus·vs code·import·unplugin
PascalMing1 个月前
TDengine 3.0+ 数据库数据导出与导入工具
tdengine·import·export·导入导出