javascriptimportecmascript-6exportbabeljs

Javascript export/import class


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');
  }
}

Solution

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

    Try

    var myInstance = new Example()
    myInstance.test()