Borislav Hadzhiev
Last updated: Jul 26, 2022
Check out my new book
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 doesn't have a
default export of a function
Having cyclic dependencies (imports and exports between the same modules)
Here is an example of how the error occurs.
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.
// ✅ Works const path = require('path'); (function () {})()
To achieve this, the function must be exported directly. Here is an example.
function logger(message) { console.log(message) } module.exports = logger;
And this is how we would import the function and invoke it directly after our
require
call.
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.
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 so that the two files don't
depend on one another, or create a third module C
that uses modules A
and
B
.