0

I am using webpack, ES6, and Babel for a project. A module had a require statement like so:

var ajaxGetJSON = require("../utils/ajaxGetJSON");

The bundle compiled fine but threw a runtime error that

Uncaught TypeError: ajaxGetJSON is not a function

Here is an examination of the object provided by webpack to my module:

enter image description here

When I change the require to an import ajaxGetJSON from "../utils/ajaxGetJSON"; the runtime error does not occur and the inspected object that should be the function ajaxGetJSON works properly.

The ajax module uses export default myObject.

Why does switching to an import fix my problem?

Alex Mcp
  • 19,037
  • 12
  • 60
  • 93

1 Answers1

1

As you can see from the debugger tooltip, require() yields an ES6 module object (which is what babel transpiles modules to) that is not a function but has the function as its .default property.

ajaxGetJSON is a default export of that module, and you should import it as such. If you are using ES6 modules, you should not use require at all.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • I'm coming to that realization now; we use require mostly when we need to use rewire to mock dependencies in our test suite. Good rule to follow. If we want to fix this for some reason, we would need to `let foo = require("foo").default` then? – Alex Mcp Feb 24 '16 at 18:26
  • Yes, that would work (until babel changes its module format - which is unlikely but [has happened before](http://stackoverflow.com/q/33505992/1048572)). – Bergi Feb 24 '16 at 18:28