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?
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.
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.
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.
That should be
import { getData } from data.js
Without the brackets, you're importing the default
export which doesn't exist.
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();
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With