7

I am trying to import a function from another module but on running am getting an error:

TypeError: _this.getData is not a function.

data.js

function getData() {
  return [
    { id: 1,
      name: 'Pluto',
      type: 'Dwarf Planet'
    },
    { id: 2,
      name: 'Neptune',
      type: 'Planet'
    }
  ]
}
export { getData }

worker.js

import getData from data.js

this.data = this.getData()

Then on run I get the browser error as mentioned above. Any ideas as to what I am doing incorrectly?

Don Smythe
  • 9,234
  • 14
  • 62
  • 105
  • 1
    google -> "es6 import syntax" -> 1. result: [MDN: import](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import) – Andreas Apr 01 '17 at 14:18
  • It's `getData` anyway, not `this`. There is no `this` in a module scope. – Bergi Apr 01 '17 at 14:29

3 Answers3

8

That should be

import { getData } from data.js

Without the brackets, you're importing the default export which doesn't exist.

Joseph
  • 117,725
  • 30
  • 181
  • 234
6

You should omit the "this" keyword when using "getData()" it doesn't belong on the current object.

function getData() { .... }

export default getData;

import getData from "data.js"

this.data = getData();
DNM
  • 1,069
  • 3
  • 12
  • 17
4

Change your import as a named import like this:

import { getData } from data.js

Or export getData function as a default export like this:

export default { getData }
Shota
  • 6,910
  • 9
  • 37
  • 67
  • This almost worked for me but it's incomplete. You have to use the braces around the name of the imported function (import { getData } from data.js), AND you have to designate the function as an export where it's defined, if you aren't going to make it an export default. So if you aren't going to export default { getData }, you have to define it as export function getData() {...}, for instance. – user1258361 Apr 21 '20 at 16:48