Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

require.context: 创建模块上下文 #17

Open
54leibo opened this issue Jun 3, 2020 · 0 comments
Open

require.context: 创建模块上下文 #17

54leibo opened this issue Jun 3, 2020 · 0 comments

Comments

@54leibo
Copy link
Owner

54leibo commented Jun 3, 2020

  • 语法:const req= require.context(directory, useSubdirectories = false, regExp = /^.//);

    • directory 加载的目录
    • useSubdirectories 是否加载子目录
    • regExp 文件名匹配正则
    • 返回值:req为一个require函数,且包含三个属性(resolve, keys, id)
      • resolve:是一个函数,它返回 request 被解析后得到的模块 id
      • keys:也是一个函数,它返回一个数组,由所有可能被此 context module 处理的请求组成。
      • id:是 context module 里面所包含的模块 id.
  • 例子1:多文件便捷载入(例子2有展示)

  • 例子2:多文件便捷载入之SVG图标解决方案(elementUI使用的该方法,除此之外还可以使用Unicode、font-class详见参考资料)

    • 说明:除了利用require.context还利用了svg-sprite-loader及svg sprite相关知识
目录说明:
svg文件夹存放svg图标并与index.js同目录存放

index.js:
import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon'// svg component

// register globally
Vue.component('svg-icon', SvgIcon)
const req = require.context('./svg', false, /\.svg$/)
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)

SvgIcon组件:
<template>
  <svg :class="svgClass" aria-hidden="true">
    <use :href="iconName" />
  </svg>
</template>

<script>
export default {
  name: 'SvgIcon',
  props: {
    iconClass: {
      type: String,
      required: true
    },
    className: {
      type: String,
      default: ''
    }
  },
  computed: {
    iconName() {
      return `#icon-${this.iconClass}`
    },
    svgClass() {
      if (this.className) {
        return 'svg-icon ' + this.className
      } else {
        return 'svg-icon'
      }
    }
  }
}
</script>

<style scoped>
.svg-icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}
</style>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant