39

I'm trying to use classes in pure JavaScript, so I'm facing the error "Uncaught SyntaxError: Cannot use import statement outside a module" and can't solve it.

File1.js - Main file

import example from "./file2";

var test = new example();

File2.js - Class file

export default class example {
    constructor() {
        console.log("hello world");
    }
}
Walter Dudley
  • 491
  • 1
  • 4
  • 3
  • 1
    Browsers cannot process `import` so you would need to use something like Babel, short explanation here: https://stackoverflow.com/a/41662216/779600 – nihiser Dec 24 '19 at 12:15
  • 1
    This question seems to be about using import statements outside of the browser, so it's different from the linked questions. – Ola Eldøy Jul 31 '20 at 08:33

2 Answers2

42

Add files with type="module":

<script src="file1.js" type="module" ></script>
KyleMit
  • 30,350
  • 66
  • 462
  • 664
marzelin
  • 10,790
  • 2
  • 30
  • 49
  • 39
    I think the OP is trying to use pure javascript sans a browser. I am using Node.Js and am having the same problem as the OP. – Nakul Tiruviluamala Feb 02 '20 at 08:53
  • "scripts": { "start": "babel-node server.js" } should work – Suhas Dhongade Apr 06 '20 at 11:15
  • 4
    what do you mean "add files with type="module". What if you're not using a script? – PositiveGuy Aug 16 '20 at 23:08
  • 1
    @PositiveGuy There are ways to execute javascript code outside of `script` tags but they rather should be avoided. If you want to know all nuts and bolts of import statements please refer to one of many comprehensive javascript books such as exploringjs.com/es6.html – marzelin Aug 18 '20 at 11:06
  • In case it is browser based, it is explained in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules#applying_the_module_to_your_html – Pere Jul 25 '21 at 15:42
4

A little late, but for newcomers to this quandary, you can convert both files to a module js .mjs. From there you can do what you were trying:

File1.mjs - Main file

import example from "./file2.mjs";

File2.mjs - Class file

export default class example {
    constructor() {
        console.log("hello world");
    }
}
Mister Pea
  • 124
  • 1
  • 4