ES2015 import doesn't work (even at top-level) in Firefox

Christoph Burschka picture Christoph Burschka · Jun 4, 2016 · Viewed 74.1k times · Source

These are my sample files:

<!DOCTYPE html>
<html>
<head>
  <title>Test</title>
  <script src="t1.js"></script>
</head>
<body></body>
</html>

t1.js:

import Test from 't2.js';

t2.js:

export const Test = console.log("Hello world");

When I load the page in Firefox 46, it returns "SyntaxError: import declarations may only appear at top level of a module" - but I'm not sure how much more top-level the import statement can get here. Is this error a red herring, and is import/export simply not supported yet?

Answer

Actually the error you got was because you need to explicitly state that you're loading a module - only then the use of modules is allowed:

<script src="t1.js" type="module"></script>

I found it in this document about using ES6 import in browser. Recommended reading.

Fully supported in those browser versions (and later; full list on caniuse.com):

  • Firefox 60
  • Chrome (desktop) 65
  • Chrome (android) 66
  • Safari 1.1

In older browsers you might need to enable some flags in browsers:

  • Chrome Canary 60 – behind the Experimental Web Platform flag in chrome:flags.
  • Firefox 54 – dom.moduleScripts.enabled setting in about:config.
  • Edge 15 – behind the Experimental JavaScript Features setting in about:flags.