使用ES6,我可以像这样从文件中导入几个导出:

import {ThingA, ThingB, ThingC} from 'lib/things';

但是,我喜欢每个文件有一个模块的组织方式。我最终得到了这样的导入:

import ThingA from 'lib/things/ThingA';
import ThingB from 'lib/things/ThingB';
import ThingC from 'lib/things/ThingC';

我希望能够做到这一点:

import {ThingA, ThingB, ThingC} from 'lib/things/*';

或者类似的东西,按照大家理解的约定,每个文件包含一个默认导出,每个模块与其文件同名。

这可能吗?


当前回答

这只是@Bergi回答的另一种方法

// lib/things/index.js
import ThingA from './ThingA';
import ThingB from './ThingB';
import ThingC from './ThingC';

export default {
 ThingA,
 ThingB,
 ThingC
}

Uses

import {ThingA, ThingB, ThingC} from './lib/things';

其他回答

类似于公认的答案,但它允许你在每次创建索引文件时不需要添加一个新模块的情况下进行扩展:

/模块/ moduleA.js

export const example = 'example';
export const anotherExample = 'anotherExample';

/模块/ index.js

// require all modules on the path and with the pattern defined
const req = require.context('./', true, /.js$/);

const modules = req.keys().map(req);

// export all modules
module.exports = modules;

。/ example.js

import { example, anotherExample } from './modules'

如果你不导出A, B, C中的默认值,而只是导出{},那么这是可能的

// things/A.js
export function A() {}

// things/B.js
export function B() {}

// things/C.js
export function C() {}

// foo.js
import * as Foo from ./thing
Foo.A()
Foo.B()
Foo.C()

你现在可以使用async import():

import fs = require('fs');

然后:

fs.readdir('./someDir', (err, files) => {
 files.forEach(file => {
  const module = import('./' + file).then(m =>
    m.callSomeMethod();
  );
  // or const module = await import('file')
  });
});

你也可以使用require:

const moduleHolder = []

function loadModules(path) {
  let stat = fs.lstatSync(path)
  if (stat.isDirectory()) {
    // we have a directory: do a tree walk
    const files = fs.readdirSync(path)
    let f,
      l = files.length
    for (var i = 0; i < l; i++) {
      f = pathModule.join(path, files[i])
      loadModules(f)
    }
  } else {
    // we have a file: load it
    var controller = require(path)
    moduleHolder.push(controller)
  }
}

然后使用动态加载控制器的moduleHolder:

  loadModules(DIR) 
  for (const controller of moduleHolder) {
    controller(app, db)
  }

只是对答案中已经提供的主题的一个变化,但是这样如何:

在一件事中,

export default function ThingA () {}

在事情/ index.js,

export {default as ThingA} from './ThingA'
export {default as ThingB} from './ThingB'
export {default as ThingC} from './ThingC'

然后去其他地方消费,

import * as things from './things'
things.ThingA()

或者只消耗一些东西,

import {ThingA,ThingB} from './things'