Fix the 'Unexpected identifier' error importing JS modules
By Flavio Copes
Learn how to fix the Unexpected identifier error when using ES module import in the browser, by adding type='module' to your script tag so imports work.
The fix for the Unexpected identifier error when importing JavaScript modules is adding type="module" to your script tag. Let’s see why.
If you are using the import statement to import different files in your JavaScript application, you might find the browser giving you this error: Unexpected Identifier.

You just have to do one tiny change: instead of loading your main entry point JavaScript file using
<script src="index.js"></script>
add type="module":
<script type="module" src="index.js"></script>
and things should now work fine.
Why does this error happen?
Without type="module", the browser loads your file as a classic script. The import and export keywords are only valid inside modules, so when the parser hits your import line, it stops with a syntax error.
The exact wording depends on the browser. Safari says Unexpected identifier. Chrome is more explicit: Uncaught SyntaxError: Cannot use import statement outside a module. Same problem, same fix.
A working example
Say you have a file that exports a function:
//cart.js
export const total = items =>
items.reduce((sum, item) => sum + item.price, 0)
and your entry point imports it:
//index.js
import { total } from './cart.js'
console.log(total([{ price: 9 }, { price: 15 }])) //24
With type="module" on the script tag, this runs. Notice the ./cart.js path includes the file extension. Browsers don’t resolve ./cart like Node or a bundler does, so leaving it off gets you a 404.
What else changes with type=“module”
Module scripts behave a bit differently from classic scripts.
They are deferred by default, so they run after the HTML is parsed. They run in strict mode. And top-level variables stay scoped to the module instead of becoming globals.
None of this usually causes trouble, but it explains why a script that “worked before” might behave differently after the switch.
It still fails when I open the HTML file directly
One more pitfall. If you open your page with a file:// URL by double-clicking the HTML file, modules won’t load. Browsers fetch modules with CORS rules, and those block local file access.
Serve the folder over HTTP instead. Any local server works, for example:
npx serve
then open the localhost address it prints.
Related posts about js: