babel: "require(...) is not a function" error while using require dynamically in babel 6.0 with node

So, I tried migrating one of my projects to babel 6.0 and encountered the following error message:

TypeError: require(...) is not a function
    at other.js:7:48
    at Array.forEach (native)
    at Object.<anonymous> (other.js:7:7)
    at Module._compile (module.js:425:26)
    at loader (/Users/yamalight/Projects/js/test/babel/node_modules/babel-core/lib/api/register/node.js:136:5)
    at Object.require.extensions.(anonymous function) [as .js] (/Users/yamalight/Projects/js/test/babel/node_modules/babel-core/lib/api/register/node.js:146:7)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:311:12)
    at Module.require (module.js:366:17)
    at require (module.js:385:17)

The error occurs when I try to read filenames from directory and then dynamically require all of them, i.e.:

import fs from 'fs';

// get local files
const files = fs.readdirSync('./test');

// require and execute each
files.forEach(file => require('./test/' + file)());

Simplified version that also fails:

require('./test.js')();

Here’s the full code that reproduces the behavior with simplified case: https://gist.github.com/yamalight/7de2b4f8ec9a48a7782f

Switching back to babel 5.x resolves the issue.

About this issue

  • Original URL
  • State: closed
  • Created 9 years ago
  • Comments: 18 (5 by maintainers)

Most upvoted comments

@lijunle I just used require(module).default() as mentioned above