Is it possible to import modules from all files in a directory, using a wildcard?

webpack import all files in directory
import all files in a folder javascript
javascript require all files in directory
react'; import all images from folder
javascript import class from another file
javascript import variable from another file
cannot use import statement outside a module
vue import all components from folder

With ES6, I can import several exports from a file like this:

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

However, I like the organization of having one module per file. I end up with imports like this:

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

I would love to be able to do this:

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

or something similar, with the understood convention that each file contains one default export, and each module is named the same as its file.

Is this possible?

I don't think this is possible, but afaik the resolution of module names is up to module loaders so there might a loader implementation that does support this.

Until then, you could use an intermediate "module file" at lib/things/index.js that just contains

export * from 'ThingA';
export * from 'ThingB';
export * from 'ThingC';

and it would allow you to do

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

ES6 import all files in a folder?, Is it possible to import modules from all files in a directory, using a wildcard? files.forEach(function (file){ import * as object from 'file'; }};. share. *(wildcard) only imports all the classes from the package, but it doesn't import all the packages inside the package, if that was possible then we can just say import java.*; But that's not right.

Just a variation on the theme already provided in the answer, but how about this:

In a Thing,

export default function ThingA () {}

In things/index.js,

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

Then to consume all the things elsewhere,

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

Or to consume just some of things,

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

Support importing multiple files via wildcards, replacing barrels , So, without the directives/index.ts file at all, we'd be able to write that the target is a folder, and then load all its modules. these are two trips to  This is nice, yet not a wildcard though - but it has the advantage on not failing due to much directories – Bonsi Scott Jan 4 '13 at 9:19 Note that this is recursive by default. If you only want your command applied to the top level you can use the -maxdepth find argument.

The current answers suggest a workaround but it's bugged me why this doesn't exist, so I've created a babel plugin which does this.

Install it using:

npm i --save-dev babel-plugin-wildcard

then add it to your .babelrc with:

{
    "plugins": ["wildcard"]
}

see the repo for detailed install info


This allows you to do this:

import * as Things from './lib/things';

// Do whatever you want with these :D
Things.ThingA;
Things.ThingB;
Things.ThingC;

again, the repo contains further information on what exactly it does, but doing it this way avoids creating index.js files and also happens at compile-time to avoid doing readdirs at runtime.

Also with a newer version you can do exactly like your example:

 import { ThingsA, ThingsB, ThingsC } from './lib/things/*';

works the same as the above.

Possible to require every file in a directory? · Issue #625 · webpack , There are some modules on npm that do this, but they all use fs. (I'm experimenting with context, but so far I was able just to import them). Python Exercises, Practice and Solution: Write a Python program to make file lists from current directory using a wildcard.

Great gugly muglys! This was harder than it needed to be.

Export one flat default

This is a great opportunity to use spread (... in { ...Matters, ...Contacts } below:

// imports/collections/Matters.js
export default {           // default export
  hello: 'World',
  something: 'important',
};
// imports/collections/Contacts.js
export default {           // default export
  hello: 'Moon',
  email: 'hello@example.com',
};
// imports/collections/index.js
import Matters from './Matters';      // import default export as var 'Matters'
import Contacts from './Contacts';

export default {  // default export
  ...Matters,     // spread Matters, overwriting previous properties
  ...Contacts,    // spread Contacts, overwriting previosu properties
};

// imports/test.js
import collections from './collections';  // import default export as 'collections'

console.log(collections);

Then, to run babel compiled code from the command line (from project root /):

$ npm install --save-dev @babel/core @babel/cli @babel/preset-env @babel/node 
(trimmed)

$ npx babel-node --presets @babel/preset-env imports/test.js 
{ hello: 'Moon',
  something: 'important',
  email: 'hello@example.com' }
Export one tree-like default

If you'd prefer to not overwrite properties, change:

// imports/collections/index.js
import Matters from './Matters';     // import default as 'Matters'
import Contacts from './Contacts';

export default {   // export default
  Matters,
  Contacts,
};

And the output will be:

$ npx babel-node --presets @babel/preset-env imports/test.js
{ Matters: { hello: 'World', something: 'important' },
  Contacts: { hello: 'Moon', email: 'hello@example.com' } }
Export multiple named exports w/ no default

If you're dedicated to DRY, the syntax on the imports changes as well:

// imports/collections/index.js

// export default as named export 'Matters'
export { default as Matters } from './Matters';  
export { default as Contacts } from './Contacts'; 

This creates 2 named exports w/ no default export. Then change:

// imports/test.js
import { Matters, Contacts } from './collections';

console.log(Matters, Contacts);

And the output:

$ npx babel-node --presets @babel/preset-env imports/test.js
{ hello: 'World', something: 'important' } { hello: 'Moon', email: 'hello@example.com' }
Import all named exports
// imports/collections/index.js

// export default as named export 'Matters'
export { default as Matters } from './Matters';
export { default as Contacts } from './Contacts';
// imports/test.js

// Import all named exports as 'collections'
import * as collections from './collections';

console.log(collections);  // interesting output
console.log(collections.Matters, collections.Contacts);

Notice the destructuring import { Matters, Contacts } from './collections'; in the previous example.

$ npx babel-node --presets @babel/preset-env imports/test.js
{ Matters: [Getter], Contacts: [Getter] }
{ hello: 'World', something: 'important' } { hello: 'Moon', email: 'hello@example.com' }
In practice

Given these source files:

/myLib/thingA.js
/myLib/thingB.js
/myLib/thingC.js

Creating a /myLib/index.js to bundle up all the files defeats the purpose of import/export. It would be easier to make everything global in the first place, than to make everything global via import/export via index.js "wrapper files".

If you want a particular file, import thingA from './myLib/thingA'; in your own projects.

Creating a "wrapper file" with exports for the module only makes sense if you're packaging for npm or on a multi-year multi-team project.

Made it this far? See the docs for more details.

Also, yay for Stackoverflow finally supporting three `s as code fence markup.

Modules · TypeScript, At runtime the module loader is responsible for locating and executing all Conversely, a file without any top-level import or export declarations is treated as a Wildcard module declarations can be used to cover these cases. Consumers of your module should have as little friction as possible when using things that you  1. The first macro creates a list of all sheets within all excel files . 2. The second macro reads each of these files paths (with sheet names) and reads the data into Alteryx. You will need to update the directory tool and make sure you are reading in xlsx files as that is what this workflow is configured to take.

You can use async import():

import fs = require('fs');

and then:

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

import, Even though the glob API is very simple, the module packs a lot of power. import glob for name in glob.glob('dir/*'): print name. The pattern matches every pathname (file or directory) in the directory dir, If there was another subdirectory, the wildcard would match both subdirectories and include the filenames from both. Imported modules are in strict mode whether you declare them as such or not. The import statement cannot be used in embedded scripts unless such script has a type="module". There is also a function-like dynamic import(), which does not require scripts of type="module".

glob – Filename pattern matching, Module: Microsoft.PowerShell. Get-ChildItem displays the files and directories in the PowerShell console. Path uses the asterisk ( * ) wildcard to specify all files with the filename extension .txt . Accepted values: Archive, Compressed, Device, Directory, Encrypted, Hidden, IntegrityStream, Normal, NoScrubData,  Importing a Module-System File permalink Importing a Module-System File When you import a file that contains @use rules, the importing file has access to all members (even private members) defined directly in that file, but not any members from modules that file has loaded.

Get-ChildItem, In addition to the standard algorithm, all asset types supported by Parcel are also resolved. Module Globs are wildcard imports that bundle multiple assets at once. This example bundles a directory of png files and returns the dist URLs. By default, you can't. When importing a file, Python only searches the current directory, the directory that the entry-point script is running from, and sys.path which includes locations such as the package installation directory (it's actually a little more complex than this, but this covers most cases).

Module Resolution, import os >>> dir(os) <returns a list of all module functions> >>> help(os) The glob module provides a function for making file lists from directory wildcard  The combination of wildcard delimiter (*) following a slash (/) as part of the search criteria is interpreted by AML as a comment indicator. As a result, the rest of the line is ignored. Solution: To be able to search a directory using the wildcard delimiter you need to enclose the path within single quotes. 1) This example specifies the path directly:

Comments
  • This is possible. Please see module documentation for babel babeljs.io/docs/learn-es2015 ... guoted "import {sum, pi} from "lib/math";". The accepted answer is no more valid. Please update it.
  • @kresli I don't think you understand the question. In the docs, lib/math is a file containing multiple exports. In my question, lib/math/ is a directory containing several files, each containing one export.
  • ok, I see. In that case Bergi is correct. Sorry
  • Thanks for the help. I was able to get this working with index.js looking like: import ThingA from 'things/ThingA'; export {ThingA as ThingA}; import ThingB from 'things/ThingB'; export {ThingB as ThingB};. Other incantations in index.js wouldn't budge.
  • Hm, export * from should work. Have you tried …from './ThingA' or export ThingA from …? What module loader are you using?
  • Yes, your original answer did work if each ThingA.js, ThingB.js, each exported named exports. Spot on.
  • Do you have to specify the index file or can you specify just the folder and index.js will be loaded instead?
  • @Zorgatone: That depends on the module loader you are using, but yes usually the folder path will be enough.
  • Wanna have a look at @wolfbiter's answer? Not sure why he claims parenthesis don't work.
  • @Bergi Yeah agree, I don't think wolfbiter's is valid ES6. Maybe he's using an old version of Babel, or some other transpiler?
  • How is this being transpiled? Importing a directory doesn't resolve to index.js for me. I'm using SystemJs + Babel