Javascript export/import class
100,583
Solution 1
You are only importing the class, but not making an instance of the class
Try
var myInstance = new Example()
myInstance.test()
Solution 2
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.
Related videos on Youtube
Author by
Alan P.
Updated on July 19, 2022Comments
-
Alan P. almost 2 years
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'); } }