简体   繁体   中英

"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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM