使用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/*';

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

这可能吗?


当前回答

我用过它们几次(特别是在构建大型对象时,将数据拆分到多个文件中(例如AST节点)),为了构建它们,我做了一个小脚本(我刚刚添加到npm中,以便其他人都可以使用它)。

使用方法(目前你需要使用babel来使用导出文件):

$ npm install -g folder-module
$ folder-module my-cool-module/

生成包含以下内容的文件:

export {default as foo} from "./module/foo.js"
export {default as default} from "./module/default.js"
export {default as bar} from "./module/bar.js"
...etc

然后你就可以使用这个文件了:

import * as myCoolModule from "my-cool-module.js"
myCoolModule.foo()

其他回答

如果你使用webpack。这将自动导入文件并导出为api命名空间。

所以不需要更新每一个文件添加。

import camelCase from "lodash-es";
const requireModule = require.context("./", false, /\.js$/); // 
const api = {};

requireModule.keys().forEach(fileName => {
  if (fileName === "./index.js") return;
  const moduleName = camelCase(fileName.replace(/(\.\/|\.js)/g, ""));
  api[moduleName] = {
    ...requireModule(fileName).default
  };
});

export default api;

对于Typescript用户;

import { camelCase } from "lodash-es"
const requireModule = require.context("./folderName", false, /\.ts$/)

interface LooseObject {
  [key: string]: any
}

const api: LooseObject = {}

requireModule.keys().forEach(fileName => {
  if (fileName === "./index.ts") return
  const moduleName = camelCase(fileName.replace(/(\.\/|\.ts)/g, ""))
  api[moduleName] = {
    ...requireModule(fileName).default,
  }
})

export default api

Nodejs吗?这样做:

用index.js创建一个文件夹,在索引文件中添加以下内容:

var GET = require('./GET');
var IS = require('./IS');
var PARSE = require('./PARSE');
module.exports = { ...GET, ...IS, ...PARSE};

并且,在GET.js或IS.js文件中正常导出:

module.exports = { /* something as you like */}

现在,你只需要像这样包含index.js:

const Helper = require('./YourFolder');

Helper将包括你文件夹中的所有功能。

美好的一天!

如果你不导出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()

我可以借鉴用户atilkan的方法并稍加修改:

对于Typescript用户;

require.context('@/folder/with/modules', false, /\.ts$/).keys().forEach((fileName => {
    import('@/folder/with/modules' + fileName).then((mod) => {
            (window as any)[fileName] = mod[fileName];
            const module = new (window as any)[fileName]();

            // use module
});

}));

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

在一件事中,

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'