SyntaxError: Cannot use import statement outside a module

I am following along Mosh at the beginning of his Redux course when he improts Map from immutable but, unlikely him, I am getting this error SyntaxError: Cannot use import statement outside a module.
This is my code:
import { Map } from ‘immutable’;
let book = Map({ title: ‘Harry Potter’ });
console.log(book)

Googling around hasn’t been very helpful and actually, it made me more confused.

Any tips?

I have the same issue. Did you find a solution? I tried everything I could find on stackoverflow, no luck.

What command are you using to start your React app?

I’m using npm start then open with live server. Could that be somehow connected?

Maybe. I’m not sure why you would need to use live server. For me, npm start starts up a development server on port 3000 and a browser window automatically opens and takes me to my React app at http://localhost:3000/

I see. In my case it wouldn’t open with just the npm start command. I think it has to do with the package.json file, but I didn’t want to mess it up even more before finding a solution for this issue. From my research so far I might need to use require JS to be able to use the import. I just wonder how others did it without it. As I understand most people didn’t encounter this issue, judging by the comments.

Update. I’m not sure whether this is what solved it, but I installed webpack-cli and webpack globally, and now it works. I might have tweaked things here and there, so not sure if this was the reason.

The “Cannot use import statement outside a module” error in JavaScript arises when attempting to utilize the import statement to load modules in a context that isn’t recognized as a module. To rectify this, ensure your JavaScript file is treated as a module by adding type=“module” to the HTML script tag that loads it, use the import statement at the module-level scope, serve code from a server rather than directly opening HTML files, provide correct file extensions, validate file structure and paths, use a browser version supporting ES modules, and differentiate between Node.js (CommonJS) and browser (ES module) usage.