0

I'm trying to use a class from A.js file in B.js file, i made an instance of A.js class and tried to call its function in B.js, but i got an error saying

Uncaught SyntaxError: Cannot use import statement outside a module

this is what the code looks like:

A.js file

export class A {
    constructor() {
        this.name = 'A'
    }
    getName() {
        return this.name;
    }
}

B.js file

import A from './A.js';
const a = new A();
console.log(a.getName());

what am i doing wrong?

2 Answers2

1

In your file B.js, change the import from import A from './A.js'; to import { A } from './A.js';

There are two ways to export a class or a function:

1) default

2) named

1) allows a single export per file. The naming of import is independent of the original exported name.

Example:

export default class A { } // A.js
import AComponent from './A'; 

2) allows multiple exports per file. The name of the import has to be the same as the name of the export.

Example:

export class A { } // A.js
import { A } from './A'; 
Umair Sarfraz
  • 5,284
  • 4
  • 22
  • 38
0

You need to use keyword default if you are using import without {}. try a code like below -

export default class A {
    constructor() {
        this.name = 'A'
    }
    getName() {
        return this.name;
    }
}

Or you can use alias like this -

import * as A from './A.js';
Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215
  • While that's correct, the OP's current problem is that they are not loading the code as a module. *"Or you can use alias like this"* Then they would have to access the class with `A.A` though... – Felix Kling Oct 15 '19 at 13:54