index.js 704 B

123456789101112131415161718192021222324252627282930
  1. const _ = require('lodash')
  2. const fs = require('fs')
  3. const path = require('path')
  4. /**
  5. * 映射 d 文件夹下的文件为模块
  6. */
  7. const mapDir = d => {
  8. const tree = {}
  9. // 获得当前文件夹下的所有的文件夹和文件
  10. const [dirs, files] = _(fs.readdirSync(d)).partition(p => fs.statSync(path.join(d, p)).isDirectory())
  11. // 映射文件夹
  12. dirs.forEach(dir => {
  13. tree[dir] = mapDir(path.join(d, dir))
  14. })
  15. // 映射文件
  16. files.forEach(file => {
  17. if (path.extname(file) === '.js') {
  18. tree[path.basename(file, '.js')] = require(path.join(d, file))
  19. }
  20. })
  21. return tree
  22. }
  23. // 默认导出当前文件夹下的映射
  24. module.exports = mapDir(path.join(__dirname))