Home > database >  "Cannot use import statement outside a module" and "Uncaught SyntaxError: Unexpected
"Cannot use import statement outside a module" and "Uncaught SyntaxError: Unexpected

Time:11-02

I'm trying to import a class into my "main.js" file. Here is a minified version of my code.

// "extended.js" file

export default class Test {
  constructor() {
    this.prop = "Hello"
    console.log(this.prop)
  }
}


// "main.js" file

window.onload = function () {
  import Test from "./extended"
  new Test()
}

The main.js file is the frontend JavaScript file for my Express app so it is stored in the "public" folder. When you load the page the initial error that occurs is "Cannot use import statement outside a module". I've done research on my own and multiple people have stated that using type="module" for the "main.js" script tag will resolve the issue. When I did that the error changed to "Uncaught SyntaxError: Unexpected identifier". Is there something I'm missing about how to use ES6 modules and classes?

CodePudding user response:

You can only import at the top level - it can't be done inside a block. Change

window.onload = function () {
  import Test from "./extended"
  new Test()
}

to

import Test from "./extended"
window.onload = function () {
  new Test()
};

Though, I'd also suggest not creating classes for side-effects - if you just want the class to do something, but not to return something useful, use a plain function instead.

export default () => {
  const prop = "Hello";
  console.log(prop);
};
  • Related