node下自动import文件夹下所有js文件的模块(一)

864 阅读1分钟
简单高效的方法一

在指定目录下新建index.js文件作为入口,复制以下代码,其会自动导入当前目录及子目录的默认导出模块

const files = require.context('./', true, /\.js$/)
function importAllModule(files) {
  const map = {}
  let tmp = {}
  for (let key of files.keys()) {
      map[key] = files(key).default
  }
  for (let key in map) {
      tmp = {
          ...tmp,
          ...map[key]
      }
  }
  return tmp
}

export let bgcApi = importAllModule(files)

同目录下其他js文件使用默认导出


export default { myfetch }

其他引用文件直接导入index即可

import  bgcApi from './src/api/bgcApi/index'

//  效果等同于 import { myfetch, myfetch2, myfetch3  } from './src/api/bgcApi/index'

订制化改进的方法二 (待更新)