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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM