41

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");
    }
}
2
  • 1
    Browsers cannot process import so you would need to use something like Babel, short explanation here: stackoverflow.com/a/41662216/779600 Commented Dec 24, 2019 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. Commented Jul 31, 2020 at 8:33

3 Answers 3

45

Add files with type="module":

<script src="file1.js" type="module" ></script>
Sign up to request clarification or add additional context in comments.

5 Comments

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.
"scripts": { "start": "babel-node server.js" } should work
what do you mean "add files with type="module". What if you're not using a script?
@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
In case it is browser based, it is explained in developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/…
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");
    }
}

Comments

0

add "type": "module" in package.json

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.