14

I know I can require a file in ES6 like this:

require('./config/auth');

When I try to do this

require('./config/');

I get: Module not found: Error: Cannot resolve directory './config'. Why does this happen? How can I require a directory?

Jason Swett
  • 38,405
  • 60
  • 193
  • 322

2 Answers2

4

First of all, your requires are in NodeJS/io.js syntax, module in ES6 syntax looks like this:

import "./config/auth";

Or if you want to load something from it:

import authenticate from "./config/auth";

You can't load whole directories at once, but in Node/io.js you can create a module and then load that.

Note that as a workaround you can load a single file that in turn loads multiple files and returns their results. There is also work in progress on an asynchronous loader but that changes so often it's hard to keep track so I wouldn't rely on it just yet.

Benjamin Gruenbaum
  • 246,787
  • 79
  • 474
  • 476
  • 12
    Maybe a loader that supported something like `import "./config/*"` wouldn't be a bad idea – Bergi May 02 '15 at 11:51
  • @Bergi it's pretty easy to do it asynchronously using SystemJS (fs.readdirAsync .map load) - the problem is SystemJS is undergoing changes and it's also async (unlike what OP is doing). – Benjamin Gruenbaum May 02 '15 at 11:52
3

I personally use a package called require-dir. This should work for you:

import requireDir from 'require-dir';
requireDir('./config');
Grzegorz Pawlik
  • 2,083
  • 1
  • 17
  • 16
  • 3
    a meta-require? require something to require something... lol – igorsantos07 Oct 29 '16 at 15:22
  • 5
    @igorsantos07 Welcome to JS :) – Mark K Cowan Jun 08 '17 at 17:09
  • This is not a good idea as it assumes that modules are files in a directory at runtime, which is not the case in many build systems. If you do this, your code can break as soon as you try to port it to another build system. – opyh Jul 28 '17 at 14:46