Why is this example below not outputting "hello world"? Instead, I am getting:
TypeError: _base2.default.test is not a function
(it is being transpiled with Babel)
file1.js
import Example from './file2'; console.log(Example.test());
file2.js
export default class Example { test() { console.log('hello world'); } }
You are only importing the class, but not making an instance of the class
Try
var myInstance = new Example() myInstance.test()
If you want to call a method as a class method (without creating an object instance) you can try static methods.
You can change the file2.js as,
export default class Example { static test() { console.log('hello world'); } }
then call it by using the class name in file1.js as
import Example from './file2'; console.log(Example.test());
Refer James Maa answer if you want to call it as an instance method.
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