Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

269
Views
"Cannot use import statement outside a module" and "Uncaught SyntaxError: Unexpected identifier" when importing a class

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);
};
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!