Search code examples
javascriptcommonjswebpackmethod-invocation

CommonJS Illegal invocation error when calling function on module.exports


Doing this works fine:

var requestAnimationFrame = 
    window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame;

function _test() {
    console.log('hello from test');
}

requestAnimationFrame(_test);

However moving this to another file and exporting it using CommonJS/webpack results in:

Uncaught TypeError: Illegal invocation

(like so:)

module.exports.requestAnimationFrame = 
    window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame;

...

var poly = require('../utils/polyfills');
poly.requestAnimationFrame(_test);

It's probably super obvious but in my mind I don't get why that wouldn't work :/


Solution

  • I found the answer here: Why are certain function calls termed "illegal invocations" in JavaScript?

    It seems some native functions depend on context, so to fix this I bind to window:

    module.exports.requestAnimationFrame = 
        (window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame).bind(window);