zoukankan      html  css  js  c++  java
  • require.context()

    用法:

    接受三个参数(require.context(directory,useSubdirectories,regExp))

    directory:说明需要检索的目录
    useSubdirectories:是否检索子目录
    regExp: 匹配文件的正则表达式,一般是文件名

    返回参数

    require.context返回一个require 函数,此函数可以接收一个参数

    返回的函数:function webpackContext(req) {return __webpack_require__(webpackContextResolve(req))};

    函数有三个属性:resolve 、keys、id

            · resolve: 是一个函数,他返回的是被解析模块的id ,接受一个参数request。

            · keys: 也是一个函数,他返回的是一个数组,该数组是由所有可能被上下文模块解析的请求对象组成

            · id:上下文模块的id

    应用场景:

    如果页面需要导入多个组件时,一般的写法

    import aaa from '@/components/login/aaa'
    import bbb from '@/components/login/bbb'
    import ccc from '@/components/login/ccc'
    import ddd from '@/components/login/ddd'
    components:{
        aaa,
        bbb,
        ccc,
        ddd,
    }

    此时可以看出代码重复量很大

    使用require.context()时的写法就简洁了许多

    const path = require('path')
    const files = require.context('@/components/login', false, /.vue$/)
    const modules = {}
    files.keys().forEach(key => {
      const name = path.basename(key, '.vue') // 提取出用 ‘/' 隔开的path的最后一部分,path.basename(p, [ext])。 p要处理的path,ext要过滤的字符
      modules[name] = files(key).default || files(key)
    })
    components:modules 

    files此时是一个函数

    files.keys()属性方法执行后会返回一个数组:["./aaa.vue", "./bbb.vue", "./ccc.vue", "./ddd.vue"]

    files.resolve('./aaa.vue')属性方法传入一个login文件下的相对路径('./aaa.vue')会返回匹配到的文件的绝对路径("./src/components/login/aaa.vue")

  • 相关阅读:
    luogu4345 [SHOI2015]超能粒子炮·改(组合数/Lucas定理)
    关于 centos 7系统,iptables透明网桥实现
    C 语言实现字符串替换
    linux 程序调用system执行命令
    linux C/C++ 日志打印函数
    关于socket编程获取客户端地址笔记
    C# treeview 使用笔记
    SIP DB33标准笔记 监控图像获取
    SIP DB33标准笔记 注册/目录发送/心跳
    contos 7/redhat 7 安装mysql
  • 原文地址:https://www.cnblogs.com/wangxirui/p/11765791.html
Copyright © 2011-2022 走看看