Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript import function syntax [duplicate]

Tags:

javascript

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?

like image 259
Don Smythe Avatar asked Apr 01 '17 14:04

Don Smythe


People also ask

What is dynamic import in JavaScript?

Dynamic imports or Code Splitting is the practice of breaking up your JavaScript modules into smaller bundles and loading them dynamically at runtime to improve and increase the performance of your website dramatically.

What is in JavaScript import?

Javascript import statement is used to import bindings that are exported by another module. Using import, the code is easier to manage when it is small and bite-size chunks. This is the thinking behind keeping functions to only one task or having files contain only a few or one component at a time.

What is require () in JavaScript?

1) require() In NodeJS, require() is a built-in function to include external modules that exist in separate files. require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object.


3 Answers

That should be

import { getData } from data.js

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

like image 140
Joseph Avatar answered Oct 19 '22 00:10

Joseph


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();
like image 32
DNM Avatar answered Oct 19 '22 00:10

DNM


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 }
like image 38
Shota Avatar answered Oct 19 '22 02:10

Shota