vue3+vite批量导出文件使用import.meta代替require.context

对于webpack来说,可以使用require.context方法来实现文件的批量导出,但是vite搭建vue3项目时,不支持require,对于这种情况可以使用import.meta.glob或者import.meta.globEager来实现

二者使用方法相似,只是引入时机不同,globEager时立即引入,glob是异步引入

globEager

 const directives = import.meta.globEager('./*/index.js')
  for (let com in directives) {
    const comKey = com.match(/\.\/(.*?)\/index\.js/)[1]
    const comValue = directives[com].default
    app.directive(comKey, comValue)
  }

image-20210927164224060

glob

  const directives = import.meta.glob('./*/index.js')
  for (let dire in directives) {
    const direKey = dire.match(/\.\/(.*?)\/index\.js/)[1]
    directives[dire]().then((res) => {
      const direValue = res.default
      app.directive(direKey, direValue)
    })
  }

image-20210927164348127

原文地址:https://www.cnblogs.com/baifangzi/p/15343723.html