Fix - require(...) is not a function TypeError in Node.js

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

banner

Photo by Thom Holmes

Fix - require(...) is not a function TypeError in Node.js #

The "require(...) is not a function" error occurs for multiple reasons:

  • Forgetting to place a semicolon between the require call and an IIFE

  • Calling the result of require() when the imported file does not have a default export of a function

  • Having cyclic dependencies (imports and exports between the same modules)

typeerror require is not a function

Here is an example of how the error occurs.

index.js
const path = require('path') // โ›”๏ธ TypeError: require(...) is not a function (function () {})()

We didn't place a semicolon after we required the path module, so the JavaScript engine assumed that the parenthesis wrapping our immediately invoked function expression are actually an argument list for another call of the result returned from require.

To solve the "require(...) is not a function" error, make sure to place a semicolon between your require call and an immediately invoked function expression and clean up any cyclic dependencies from your code.

index.js
// โœ… Works const path = require('path'); (function () {})()
You might also get the error when trying to directly call a function that is exported from another file.

To achieve this the function must be exported directly, here is an example.

another-file.js
function logger(message) { console.log(message) } module.exports = logger;

And this is how we would import this function and invoke it directly after our require call.

index.js
require('./another-file.js')('MESSAGE FOR LOGGER');

Note that if you use a named export with module.export = {logger}, you would have to require using curly braces and invoke the function on another line.

The error also occurs if you have a cyclic dependencies between modules.

For example, if module A and module B import and export files between each other, the engine gets confused as to which file should be ran first as both of the files depend on one another.

To solve this, you should either refactor your code that the two files don't depend on one another or create a third module C that uses modules A and B.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee