Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript export/import class [duplicate]

Tags:

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');   } } 
like image 201
Alan P. Avatar asked Sep 22 '17 04:09

Alan P.


2 Answers

You are only importing the class, but not making an instance of the class

Try

var myInstance = new Example() myInstance.test() 
like image 60
James Maa Avatar answered Oct 01 '22 22:10

James Maa


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.

like image 27
prabushitha Avatar answered Oct 01 '22 23:10

prabushitha